所以每次我使用while循环从文件中读入字符串时,总会有一个额外的空字符串最后被处理。ifstream fin("A7infile.txt");
while(getline(fin,line))
{
cout<<"Original Line: "<<line<<endl<<endl;
breakup(line,first,middle,last);
cout<<first<<" :is first"<<endl;
cout<<middle<<" :is middle"<<endl;
cout<<last<<" :is last\n"<<endl;
neww=makealpha(first,middle,last);
cout<<neww<<" :is the alphabetized line\n"<<endl;
}
fin.close();
return 0;这就是我所说的空字符串
Original Line: lolipops And Rainbows
lolipops :is first
And :is middle
Rainbows :is last
And Rainbows lolipops :is the alphabetized line
Original Line:
:is first
:is middle
:is last
:is the alphabetized line如何处理最后一次传递中的空字符串?
发布于 2016-05-16 06:45:03
std::string::empty (reference)可用于检查std::string是否为空。
因此,检查line是否为空,如果不为空,则运行代码,否则什么也不做。
示例:
while (getline(fin, line))
{
if (!line.empty())
{
// Your logic here...
}
}发布于 2016-05-16 06:40:05
如果你想跳过文件中的空行,在文件的末尾或中间,你可以在循环的主体中添加一个检查来跳过它们:
while(getline(fin,line)) {
if (line.empty()) {
continue;
}
// the rest of your code goes ehre
}https://stackoverflow.com/questions/37244419
复制相似问题