逐行读取文件到变量和循环

问题描述 投票:5回答:3

我有一个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
3个回答
6
投票
#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; }

3
投票
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无论如何还是失败(例如,在文件末尾),循环将结束。


1
投票
#include <fstream> using namespace std; ifstream input("phone.txt"); for( string line; getline( input, line ); ) { //code }
© www.soinside.com 2019 - 2024. All rights reserved.