如何使用getline从文件中读取到数组
How to use getline to read from a file into an array
我可以在此问题上使用您的帮助。我有一个包含以下内容的文件:
1x+1y+1z=5
2x+3y+5z=8
4x+0y+5z=2
我必须将其存储到字符串中。存储后,输出应该是这样的:
1x+1y+1z=5
a=1 b=1 c=1 d=5
2x+3y+5z=8
a=2 b=3 c=5 d=8
4x+0y+5z=2
a=4 b=0 c=5 d=2
这是我拥有的代码,但是它没有输出任何内容。有谁能够帮助我?这给了我第19行的错误,但我不知道如何解决。错误指出"呼叫无匹配函数。"
| 19 |错误:无匹配函数呼叫 'std :: basic_ifstream :: getline(std :: string [10],int)'| | 22 |错误:无匹配函数呼叫 'std :: basic_istringstream :: basic_istringstream(std :: string [10])'|
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
ifstream file("matrix.txt");
if (!file)
{
cout << "Could not open input filen";
return 1;
}
for (string line[10]; file.getline(line, 10); )
{
cout << line << 'n';
istringstream ss(line);
double a, b, c, d;
char x, y, z, eq;
if (ss >> a >> x >> b >> y >> c >> z >> eq >> d)
{
if (x == 'x' && y == 'y' && z == 'z' && eq == '=')
{
cout << "a = " << a
<< " b = " << b
<< " c = " << c
<< " d = " << d << 'n';
}
else
{
cout << "parse error 2n";
}
}
else
{
cout << "parse error 1n";
}
}
}
有几个错误。
错误没有。1
您不能也不应声明string line[10]
。您也不应使用for
循环。这是从流的字符串读取字符串的经典实现:
string line;
while (file >> line) {
... // do stuff
}
错误没有。2
您的数字是INT,而不是双打,因此您应该使用:
int a, b, c, d;
将值保存到数组
首先,我说,没有充分的理由使用原始数组。您应该始终更喜欢使用标准ADT,例如std :: vector。
在这种情况下,您不应将值直接读取到向量中,因为该值可能是不正确的。
相反,请按照以下顺序:
vector<string> lines;
string line;
while (file >> line) {
... // do stuff
if (successful)
lines.push_back(line);
}
这是读取文件并插入数组的代码。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int MAX_LINES = 100;
int main() {
std::string strArray[MAX_LINES];
fstream newFile;
newFile.open("matrix.txt", ios::in); //open a file to perform read operation
if (newFile.is_open()) { //checking whether the file is open
string tp;
for (int counter = 0; getline(newFile, tp); counter++) { // get new line
strArray[counter] = tp; // read into string array
cout << tp << "n"; //print the string
}
newFile.close(); //close the file object.
}
return 0;
}
相关文章:
- 当我在 CLion 中读取数组中的 txt 文件时C++编码问题
- For 循环在尝试读取数组 c++ 时程序崩溃
- 从文件中读取数组没有给出正确的值?
- (C/C++)fscanf_s从txt文件以字符形式读取数组时缺少整数参数错误
- C++:无法读取数组中的内容
- 读取数组的第一个元素还是第 4000 个元素更快?
- 为什么并行读取数组会导致内存泄漏?
- 读取数组中每个对象的所有键值对
- C++ 从指定范围内的文件中读取数组
- MPI_Get仅从共享内存区域读取数组的第一个元素
- 如何使用指针函数编写/读取数组
- 程序仅读取数组中 6 个值中的 4 个
- ARDUINO LCD:通过读取数组生成导航菜单
- 如何从 Arduino 库中读取数组
- 尝试创建一个读取数组并打印质数的程序
- 因为每个循环都读取数组错误
- 在 Linux 上使用 Getenv 在 C++ 中读取数组环境变量
- 如何在c++中读取数组中的输入文件
- 动态设置数组大小并从文本文件中读取数组值
- 从boost::p roperty_tree读取数组显示为空白