gpt4 book ai didi

C++从文本文件读取到数组/字符串

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:04:35 25 4
gpt4 key购买 nike

这是我目前的代码。

我需要做的是从两个不同的文本文件 Matrix A 和 Matrix B 中读取。

我可以做到这一点,但是对于我阅读的每个文本文件矩阵,它只会出现

1 0 0 

(所以基本上是第一行)实际上是 Matrix A 的整个文本文件

1 0 0
2 0 0
3 0 0

那么有人知道我该怎么做吗?

谢谢!

#include <iostream>  //declaring variables
#include <iomanip>
#include <string>
#include <fstream>

using namespace std;
string code(string& line);
int main()
{
ofstream outf;
ifstream myfile;
string infile;
string line;
string outfile;

cout << "Please enter an input file (A.txt) for Matrix A or (B.txt) for Matrix B" << endl;
cin >> infile; //prompts user for input file

if (infile == "A.txt")
{ //read whats in it and write to screen
myfile.open("A.txt");
cout << endl;
getline (myfile, line);
cout << line << endl;

}
else
if (infile == "B.txt")
{
myfile.open("B.txt");
cout << endl;
getline (myfile, line);
cout << line << endl;
}
else
{
cout << "Unable to open file." << endl;
}
//{
//while("Choose next operation");
//}
return 0;
}

最佳答案

好吧,getline 显然得到一行。

您应该逐行阅读直到文件末尾,您可以通过以下方式实现这一点,例如:

while (getline(myfile, line))
out << line << endl;

这意味着:当有一行要从 myfile 中获取时,将该行写入输出流。

关于C++从文本文件读取到数组/字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23172166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com