gpt4 book ai didi

c++ - 逐行读取文件到变量并循环

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:11:42 33 4
gpt4 key购买 nike

我有一个 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 是第 2 行,处理所有内容并循环直到文件最后一行结束。

请帮忙。我真的是 C++ 的新手。谢谢。

最佳答案

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

#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;
}

关于c++ - 逐行读取文件到变量并循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13533210/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com