在c++中从外部文件扫描完整的一行
Scanning a complete line from a external file in C++
在c++中扫描文件中的一整行:
当我使用inFile >> s;
时,其中s是一个字符串,inFile是一个外部文件,它只是从行中读取第一个单词。
完整代码:(我只是试图逐行扫描文件并打印行长度。)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inFile;
inFile.open("sample.txt");
long long i,t,n,j,l;
inFile >> t;
for(i=1;i<=t;i++)
{
inFile >> n;
string s[n];
for(j=0;j<n;j++)
{
getline(inFile,s[j]);
l=s[j].length();
cout<<l<<"n";
}
}
return 0;
}
Sample.txt
2
3
ADAM
BOB
JOHNSON
2
A AB C
DEF
第一个整数是测试用例,后面没有后面的单词。
使用std::getline函数;它就是为了这个目的而造的。你可以在这里读到。在您的特定情况下,代码将是:
string s;
getline(infile, s);
// s now has the first line in the file.
要扫描整个文件,您可以将getline()放入while循环中,因为它在文件末尾返回false(或者如果读取了坏位)。因此,您可以这样做:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inFile;
inFile.open("sample.txt");
int lineNum = 0;
string s;
while(getline(infile, s) {
cout << "The length of line number " << lineNum << " is: " << s.length() << endl;
}
return 0;
}
相关文章:
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 从C++dll访问C#中的一行主要参数
- 在C++中,我如何接受不同于同一行的用户输入
- 如何从一行中读取特定数量的字符?(C++)
- 读取最后一行代码算法 - c++ 时出现问题
- 查找矩阵C++中每一列和每一行的最小和最大元素
- 有没有办法在一行中填充矢量图
- 需要将一行代码从C++ Qt翻译成PyQt
- 为什么如果我添加这一行,我的程序会不断询问值
- 如何使代码打印文本文件中的第一行?
- 如何在C++中以这种方式返回一行文本?
- 如何使用运算符在同一行中多次调用函数
- 如何格式化我的文本文件以使其不会一遍又一遍地重复同一行?
- 而(!inputfile.eof())只读取第一行?
- 这段代码的最后一行在做什么?
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- C++找出覆盖同一行的数组
- 如何让字符数组在一行而不是多行中打印出来?