【问题标题】:Read file with multiple spaces word by word c++逐字读取具有多个空格的文件c ++
【发布时间】:2016-05-31 09:16:55
【问题描述】:

我想逐字读取 .txt 文件并将单词保存为字符串。问题是.txt文件每个单词之间包含多个空格,所以我需要忽略空格。

这是我的 .txt 文件的示例:

John      Snow  15
Marco  Polo     44
Arya    Stark   19

如你所见,每一行都是另一个人,所以我需要单独检查每一行。

我猜代码一定是这样的:

ifstream file("input.txt");
string   line;

while(getline(file, line))
{
    stringstream linestream(line);
    string name;
    string surname;
    string years;

    getline(linestream, name, '/* until first not-space character */');
    getline(linestream, surname, '/* until first not-space character */');
    getline(linestream, years, '/* until first not-space character */');

   cout<<name<<" "<<surname<<" "<<years<<endl;
}

预期结果必须是:

John Snow 15
Marco Polo 44
Arya Stark 19

【问题讨论】:

标签: c++ ifstream


【解决方案1】:

您可以只使用istream 中的operator&gt;&gt;,它会为您处理多个空格:

ifstream file("input.txt");
string   line;

while(!file.eof())
{
    string name;
    string surname;
    string years;

    file >> name >> surname >> years;

    cout<<name<<" "<<surname<<" "<<years<<endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-03
    • 2022-01-25
    • 2021-09-07
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多