在 C++ 中逐行读取并从行中获取单词
Reading line by line and fetch word from line in C++
string line;
string filename;
cout << "Please enter filename :" << endl;
cin >> filename;
ifstream myfile(filename);
/*cout << "Please enter the name of file that you write results : "<< endl;
cin >> wfile; */
if(myfile.is_open())
{
while(getline(myfile,line))
{
convert(line);
}
//getline(myfile,line);
//pushintoVector(line,buffer);
}
else
{
cout << "Error : File could not be opened" << endl;
}
try{
myfile.close();
myFile.close();
}catch(exception &e1)
{
cout << endl;
}
//system("PAUSE");
return 0;
之后我想将当前行发送到另一个函数,如:
void convert(string lines)
{
myFile.open("yazici.txt");
string buf;
string convertingnum;
istringstream ss(lines);
while(ss >> buf)
{
那么我如何从一行中读取单词并根据 if-else 结构更改它并写入另一个 file.Edit: 还有确定行长度的函数或方法吗?
- 在打开输入文件的同时打开输出文件。
- 将输出流作为参数传递给
convert
,而不是每次都在函数中打开文件。
- 使用比
myfile
和 myFile
更好的名称。
ifstream inputFile(filename);
ofstream outputFile("yazici.txt");
if(inputFile.is_open())
{
while(getline(inputFile,line))
{
convert(outputFile, line);
}
}
和...
void convert(std::ostream& outputFile,
string lines)
{
string buf;
string convertingnum;
istringstream ss(lines);
while(ss >> buf)
{
outputFile << buf << std::endl; //???
}
}
string line;
string filename;
cout << "Please enter filename :" << endl;
cin >> filename;
ifstream myfile(filename);
/*cout << "Please enter the name of file that you write results : "<< endl;
cin >> wfile; */
if(myfile.is_open())
{
while(getline(myfile,line))
{
convert(line);
}
//getline(myfile,line);
//pushintoVector(line,buffer);
}
else
{
cout << "Error : File could not be opened" << endl;
}
try{
myfile.close();
myFile.close();
}catch(exception &e1)
{
cout << endl;
}
//system("PAUSE");
return 0;
之后我想将当前行发送到另一个函数,如:
void convert(string lines)
{
myFile.open("yazici.txt");
string buf;
string convertingnum;
istringstream ss(lines);
while(ss >> buf)
{
那么我如何从一行中读取单词并根据 if-else 结构更改它并写入另一个 file.Edit: 还有确定行长度的函数或方法吗?
- 在打开输入文件的同时打开输出文件。
- 将输出流作为参数传递给
convert
,而不是每次都在函数中打开文件。 - 使用比
myfile
和myFile
更好的名称。
ifstream inputFile(filename);
ofstream outputFile("yazici.txt");
if(inputFile.is_open())
{
while(getline(inputFile,line))
{
convert(outputFile, line);
}
}
和...
void convert(std::ostream& outputFile,
string lines)
{
string buf;
string convertingnum;
istringstream ss(lines);
while(ss >> buf)
{
outputFile << buf << std::endl; //???
}
}