从同样包含字符串的.txt文件中读取整数和双精度
Reading integers and double from .txt file which also contains strings
我想写一个从文件中读取文本行的程序。每行包含多个字符串、一个整数和一个双值。行数事先不知道(即程序需要读取行直到文件结束),每行的长度也不知道。while循环检查线路是否按以下方式排序:
-- string -- integer -- double --- string
Cat. 3: 18.00 Kr. [ Tvål ]
Cat. 1: 14.50 Kr. [ Äppelmos Bob ]
Cat. 1: 12.00 Kr. [ Coca Cola 2 lit. ]
Cat. 1: 18.00 Kr. [ Kroppkakor 4 st. ]
问题是最后一个字符串包含几个空格,因此程序不会将其视为一个完整的字符串。最后一个字符串像几个字符串一样被接受,我在屏幕上只看到Cat。3:18.00 Kr。而不是整个行列表。
我试着处理这样的程序:
double doubleValue;
int intValue;
string str1, str2, str3;
ifstream infile("Register.txt", ifstream::in);
while (infile >> str1 >> intValue >> str2 >> doubleValue >> str3)
{
cout << intValue << " " << doubleValue << endl;
}
提前谢谢。
这是因为operator>>
将在空白处停止解析。
要计算,您可以先使用std::getline()
读取整行。然后,解析前四个部分(通过应用std::stringstream
),最后通过再次调用std::getline()
获得剩余部分。
#include <sstream>
using namespace std;
string line;
while (getline(infile, line)) // read the whole line from the file
{
stringstream ss(line);
ss >> str1 >> intValue >> str2 >> doubleValue; // pause the first four parts
getline(ss, str3); // parse the remaining part to str3, e.g. "Kr. [ Tvål ]"
}
你可以一直使用fscanf,它会让你,只要你知道格式:
fscanf(f, "%s %d [ %[^x5D]x5D %lf", str1, &int1, str2, &double1);
我个人更喜欢scanf,这里有一个简单的表格:
fmt meaning
%s non-whitespace string
%d integer
%u unsigned integer
%ld long
%lu unsigned long
%f float
%lf double
%llf long double
它还处理特殊格式,但这超出了本文的范围。但如果你说有一个这样的文件,它是有用的:
30.1 multi word string
你可以通过阅读
scanf("%lf %[^n]n", &mydouble, strbuf);
偏好是这里的关键,但我建议你使用fscanf进行
fscanf(FILE *f, char *fmt, ...);
http://www.manpagez.com/man/3/fscanf/
多亏了herohuyong tao,它才起作用。这是一个完整的代码片段,允许读取包含字符串、整数、双精度值的.txt文件,并且只打印整数和双精度值
这是一个txt文件中的一部分。
Cat. 3: 14.50 Kr. [ Äppelmos Bob ]
Cat. 2: 12.00 Kr. [ Coca Cola 2 lit. ]
Cat. 5: 18.00 Kr. [ Kroppkakor 4 st. ]
..........
..........
解决方案如下。
using namespace std;
cout << "Category totals for last opening period: " << endl;
double doubleValue;
int intValue;
string line, str, str2, str3;
ifstream infile("Register.txt", ifstream::in);
getline(infile, line);
while (getline(infile, line))
{
stringstream infile(line);
infile >> str >> intValue >> str2 >> doubleValue;
getline(infile, str3);
cout << endl;
cout << setw(3) << str << setw(1) << intValue << setw(7) << str2 << doubleValue << str3;
cout << endl;
}
相关文章:
- 如何在c++中从文本文件中逐行读取整数
- Arduino从Txt读取整数
- 从二进制文件中读取整数数组
- 使用字符串流读取整数并将它们相加
- 如何在从文件中读取整数时使用 file.eof()?
- C++从键盘读取整数的功能
- 为什么字符串流只读取整数中的第一个数字?如何使它只在空白处移动?
- 如何从文本文件C++读取整数和特殊字符
- C++ 从控制台读取整数数组
- 从文本文件中读取整数并将它们存储到数组中
- 输入重定向读取整数和char C
- 从文件读取整数到矩阵 (c++)
- 如何读取整数直到线结束
- 从输入文件读取整数,仅存储数组C 中的唯一整数
- 从文本文件中读取整数
- 读取整数对,直到文本输入文件中的换行符
- 在C++中从文件中读取整数和字符
- 使用 MFC C++ 6.0 从 ms 访问中读取整数数据
- 从标准输入和输入值中读取整数到向量
- 从文件中读取整数到数组