【问题标题】:Read File line by line to variable and loop逐行读取文件到变量并循环
【发布时间】:2012-11-12 01:29:39
【问题描述】:

我有一个 phone.txt,例如:

09236235965
09236238566
09238434444
09202645965
09236284567
09236235965
..and so on..

如何在 C++ 中逐行处理这些数据并将其添加到变量中。

string phonenum;

我知道我必须打开文件,但是这样做之后,要如何访问文件的下一行?

ofstream myfile;
myfile.open ("phone.txt");

还有关于变量,该过程将被循环,它将使phonenum变量成为从phone.txt处理的当前行。

如果读取第一行,phonenum 是第一行,处理所有内容并循环;现在phonenum 是第二行,处理所有内容并循环直到文件的最后一行结束。

请帮忙。我对 C++ 真的很陌生。谢谢。

【问题讨论】:

标签: c++ file-handling file-io


【解决方案1】:

请阅读内联的 cmets。他们将解释正在发生的事情,以帮助您了解其工作原理(希望如此):

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

int main(int argc, char *argv[])
{
    // open the file if present, in read mode.
    std::ifstream fs("phone.txt");
    if (fs.is_open())
    {
        // variable used to extract strings one by one.
        std::string phonenum;

        // extract a string from the input, skipping whitespace
        //  including newlines, tabs, form-feeds, etc. when this
        //  no longer works (eof or bad file, take your pick) the
        //  expression will return false
        while (fs >> phonenum)
        {
            // use your phonenum string here.
            std::cout << phonenum << '\n';
        }

        // close the file.
        fs.close();
    }

    return EXIT_SUCCESS;
}

【讨论】:

  • 你好,这真的很棒。无论如何,这是正确的吗? ifstream fs("D:\Read File Test\phone.txt");
  • 无论如何最后一件事。我尝试了代码,即使我在文本文件中只有 2 行,它也会执行 3 次该过程。这是为什么呢?
  • @user1553142 不应该。我已将您的示例数据剪切/粘贴到文本文件中,它按预期执行。每个条目一个电话号码。如果您使用的是调试器,您可能需要检查 phonenum 的内容并查看第一次或最后一次迭代中存在的内容。
【解决方案2】:

简单。首先,请注意您需要ifstream,而不是ofstream。当您从文件中读取时,您将其用作输入 - 因此 ifstream 中的 i。然后你想循环,使用std::getline 从文件中获取一行并处理它:

std::ifstream file("phone.txt");
std::string phonenum;
while (std::getline(file, phonenum)) {
  // Process phonenum here
  std::cout << phonenum << std::endl; // Print the phone number out, for example
}

std::getline之所以是while循环条件,是因为它检查流的状态。如果std::getline 无论如何都失败(例如在文件末尾),则循环将结束。

【讨论】:

    【解决方案3】:

    你可以这样做:

     #include <fstream>
     using namespace std;
    
     ifstream input("phone.txt");
    
    for( string line; getline( input, line ); )
    {
      //code
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-24
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 1970-01-01
    • 2021-10-18
    相关资源
    最近更新 更多