在 C++ 中使用字符串 getline 从文本文件读取时如何 ignore/skip 空格
how to ignore/skip white spaces when reading from a textfile using string getline in c++
你好,我正在尝试开发一个可以从文本文件中读取的程序
Edward Elric : 2000 300 3000 300
Super Trunks : 100 300 4000 900
Saitama Genos:
Goku Black: 12 333 33
我希望程序开始读取每行中的分数但跳过空格,例如每条记录最多有 4 个分数,但有些记录的分数少于 4 个,用空格表示我想要程序跳过空格读取这些记录我希望重复直到文件末尾下面是我为这部分编写的代码我很困惑我将如何继续这样做任何和所有帮助表示赞赏
我会对你的程序做一些改动
使用std::ws
有效丢弃读取到std::getline
:
之间的换行符
for(std::string line; std::getline(file>> std::ws, line);)
跟踪您能够读入多少个值 value
:
std::istringstream f(scores);
size_t values_read = 0;
while(f >> values[values_read] && ++values_read < 4)
{
}
for (size_t i = 0; i < values_read; ++i)
std::cout << values[i] << " ";
std::cout << std::endl;
输出:
2000 300 3000 300
100 300 4000 900
12 333 33
我认为您可以使用 std::getline 获得更大的优势,因为它不仅获取行,而且会读取您指定的字符。例如冒号(:
):
for(std::string line; std::getline(file, line);)
{
// turn the line into a stream
std::istringstream f(line);
std::getline(f, line, ':'); // skip past ':'
// read all the numbers one at a time
for(int v; f >> v;)
std::cout << v << ' ';
std::cout << '\n';
}
输出:
2000 300 3000 300
100 300 4000 900
12 333 33
也许可以像这样使用 #include <vector>
中很棒的 std::vector
:
int main()
{
string SampleStr = "2000 300 3000 300";
vector<string> valuesSeperated;
string temp;
for(int i = 0; i < SampleStr.size(); i++)
{
if(SampleStr[i] == ' '|| SampleStr[i] == '\n')
{
valuesSeperated.push_back(temp);
temp.clear();
}
else
temp.push_back(SampleStr[i]);
}
return 0;
}
你好,我正在尝试开发一个可以从文本文件中读取的程序
Edward Elric : 2000 300 3000 300
Super Trunks : 100 300 4000 900
Saitama Genos:
Goku Black: 12 333 33
我希望程序开始读取每行中的分数但跳过空格,例如每条记录最多有 4 个分数,但有些记录的分数少于 4 个,用空格表示我想要程序跳过空格读取这些记录我希望重复直到文件末尾下面是我为这部分编写的代码我很困惑我将如何继续这样做任何和所有帮助表示赞赏
我会对你的程序做一些改动
使用
之间的换行符std::ws
有效丢弃读取到std::getline
:for(std::string line; std::getline(file>> std::ws, line);)
跟踪您能够读入多少个值
value
:std::istringstream f(scores); size_t values_read = 0; while(f >> values[values_read] && ++values_read < 4) { } for (size_t i = 0; i < values_read; ++i) std::cout << values[i] << " "; std::cout << std::endl;
输出:
2000 300 3000 300
100 300 4000 900
12 333 33
我认为您可以使用 std::getline 获得更大的优势,因为它不仅获取行,而且会读取您指定的字符。例如冒号(:
):
for(std::string line; std::getline(file, line);)
{
// turn the line into a stream
std::istringstream f(line);
std::getline(f, line, ':'); // skip past ':'
// read all the numbers one at a time
for(int v; f >> v;)
std::cout << v << ' ';
std::cout << '\n';
}
输出:
2000 300 3000 300
100 300 4000 900
12 333 33
也许可以像这样使用 #include <vector>
中很棒的 std::vector
:
int main()
{
string SampleStr = "2000 300 3000 300";
vector<string> valuesSeperated;
string temp;
for(int i = 0; i < SampleStr.size(); i++)
{
if(SampleStr[i] == ' '|| SampleStr[i] == '\n')
{
valuesSeperated.push_back(temp);
temp.clear();
}
else
temp.push_back(SampleStr[i]);
}
return 0;
}