【问题标题】:Reading in a text file to an array including spaces将文本文件读入包含空格的数组
【发布时间】:2013-02-22 04:03:35
【问题描述】:

我必须阅读这个已经存在的文本文件。这段代码可以编译并且可以工作,但它每行只读取一个单词。

例如:我的txt文件是这样的:

  • word1 word2 word3 word4
  • word5 word6 word7
  • word8 word9

但它在屏幕上输出:

  • word1
  • word2
  • word3.. 等

如何让它将 txt 文件读入包含空格的数组?

#include <iostream>
#include <fstream>
#include <string>

using namespace std; 

int main()
{
    string friendConnections[9];
    string line;
    int loop = 0;

    ifstream networkFile("network.txt");

    if (networkFile.is_open())
    {
        while (!networkFile.eof())
        {
            istream& getline (networkFile >> line);
            friendConnections[loop] = line;
            cout << friendConnections[loop] << endl;
            loop++;
        }
        networkFile.close();
    }
    else cout << "Can't open file" << endl;

    return 0;
}

【问题讨论】:

  • cout &lt;&lt; friendConnections[loop] &lt;&lt; endl; 换行
  • 如果你使用cout &lt;&lt; line 而不是cout&lt;&lt;friendConnections[loop]&lt;&lt;endl 会发生什么?
  • 顺便说一句,istream&amp; getline (networkFile &gt;&gt; line); 应该是什么意思?据我了解,它创建了一个从未使用过的名为 getline 的引用,并使用 networkFile 对其进行初始化。

标签: c++ arrays file-io


【解决方案1】:

使用while(std::getline(networkFile,line)) 代替while(networkFile.eof())istream&amp; getline (networkFile &gt;&gt; line);

istream operator&gt;&gt; 一直到你不想要的空白处。

【讨论】:

  • 非常感谢!现在完美运行!
  • @userboss22 你不接受答案?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-08
  • 2019-10-22
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 2021-02-26
相关资源
最近更新 更多