use*_*142 5 c++ file-io file-handling
我有一个phone.txt喜欢:
09236235965
09236238566
09238434444
09202645965
09236284567
09236235965
..and so on..
Run Code Online (Sandbox Code Playgroud)
如何在C++中逐行处理此数据并将其添加到变量中.
string phonenum;
Run Code Online (Sandbox Code Playgroud)
我知道我必须打开文件,但是这样做后,如何访问文件的下一行?
ofstream myfile;
myfile.open ("phone.txt");
Run Code Online (Sandbox Code Playgroud)
而且关于变量,进程将循环,它将phonenum变量当前行从phone.txt进行处理.
就像读取第一行是phonenum第一行一样,处理所有内容并循环; 现在phonenum是第二行,处理所有内容并循环直到文件最后一行的结尾.
请帮忙.我是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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14741 次 |
| 最近记录: |