逐行读取文件到变量和循环 [英] Read File line by line to variable and loop

查看:146
本文介绍了逐行读取文件到变量和循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个phone.txt文件,如:

  09236235965 
09236238566
09238434444
09202645965
09236284567
09236235965
..等等...

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

  string phonenum; 

我知道我必须打开这个文件,但是这样做后,文件的行?

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

以及变量,过程将循环,它会使 phonenum 变量当前行从phone.txt处理它。



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



请帮助。我真的很新C ++。谢谢。

解决方案

请在线阅读评论。他们会解释怎么做,以帮助你学习如何工作(希望):

pre $ #include< iostream>
#include< fstream>
#include< string>
使用namespace std;
$ b int main(int argc,char * argv [])
{
//如果存在,以读文本模式打开文件。
ifstream fs(phone.txt);

//用于逐个提取字符串的变量。
字符串phonenum;

//从输入中提取一个字符串,跳过空格
//包括换行符,制表符,form-feeds等,当
//不再有效时(EOF或坏的文件,请选择)
//表达式将返回false
(fs>> phonenum)
{
//在这里使用您的phonenum字符串。
cout<< phonenum< ENDL;
}

//关闭文件,然后打开它。
fs.close();

return EXIT_SUCCESS;
}


I have a phone.txt like:

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

How can I process this data line by line in C++ and add it to a variable.

string phonenum;

I know I have to open the file, but after doing so, what is done to access the next line of the file?

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

and also about the variable, the process will be looped, it will make the phonenum variable the current line its processing from the phone.txt.

Like if the first line is read phonenum is the first line, process everything and loop; now the phonenum is the 2nd line, process everything and loop until the end of the last line of the file.

Please help. I'm really new to C++. Thanks.

解决方案

Read the comments inline please. They will explain what is going on to assist you in learning how this works (hopefully):

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(int argc, char *argv[])
{
    // open the file if present, in read-text-mode.
    ifstream fs("phone.txt");

    // variable used to extract strings one by one.
    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.
        cout << phonenum << endl;
    }

    // close the file on the chance you actually opened it.
    fs.close();

    return EXIT_SUCCESS;
}

这篇关于逐行读取文件到变量和循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆