循环文件处理
file handling for loop
我正在制作一个简单的程序来找出不以使用文件处理开头的行数。我无法理解为什么我的循环只有 运行ning 4 次,而它显然应该 运行 0 到 1 小于行的值。这里有什么问题?
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
const int s = 80;
char str[s];
int lines = 0, a = 0, alines = 0;
ofstream fout("file6.txt", ios::out);
cout<<"Enter the number of lines you want to enter: ";
cin>>lines;
for(int i = 0; i < lines; i++)
{
cin.getline(str, 80);
fout<<str<<endl;
}
return 0;
}
我认为你应该像这样使用 ifstream 来读取文件,并使用标准的 getline 从文件中读取行:
#include <iostream>
#include <vector>
#include <queue>
#include <string>
#include <cmath>
#include <sstream>
#include <fstream>
int main()
{
std::ifstream is("file6.txt");
std::string line;
int linesToRead = 0;
std::cin>>linesToRead;
while(std::getline(is, line))
{
if(linesToRead <= 0)
break;
std::cout<<line<<std::endl;
--linesToRead;
}
return 0;
}
我正在制作一个简单的程序来找出不以使用文件处理开头的行数。我无法理解为什么我的循环只有 运行ning 4 次,而它显然应该 运行 0 到 1 小于行的值。这里有什么问题?
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
const int s = 80;
char str[s];
int lines = 0, a = 0, alines = 0;
ofstream fout("file6.txt", ios::out);
cout<<"Enter the number of lines you want to enter: ";
cin>>lines;
for(int i = 0; i < lines; i++)
{
cin.getline(str, 80);
fout<<str<<endl;
}
return 0;
}
我认为你应该像这样使用 ifstream 来读取文件,并使用标准的 getline 从文件中读取行:
#include <iostream>
#include <vector>
#include <queue>
#include <string>
#include <cmath>
#include <sstream>
#include <fstream>
int main()
{
std::ifstream is("file6.txt");
std::string line;
int linesToRead = 0;
std::cin>>linesToRead;
while(std::getline(is, line))
{
if(linesToRead <= 0)
break;
std::cout<<line<<std::endl;
--linesToRead;
}
return 0;
}