【发布时间】:2016-04-08 16:03:34
【问题描述】:
我正在尝试编写一个 c++ 程序来将包含数据(122X300 矩阵 - 制表符分隔的矩阵)的 txt 文件读入我的代码并让它显示。以下是我在广泛参考 google 和该站点上的许多类似问题后编写的代码。在运行代码时,我没有收到任何错误,但是它确实给了我大量的数字列表,我似乎无法理解。以下是代码:任何帮助都会很棒。我不知道我哪里错了。谢谢。
在考虑@ZekeMarsh 下面的评论后做了一些改变,现在的问题是我的文本数据是这样的:
我得到的输出是这样的:
行计数器不会移动到下一行,而是在递增后继续在同一行中......不知道为什么。修改后的代码如下:
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
using namespace std;
int main(){
int HEIGHT = 3;
int WIDTH = 2;
int array_req[HEIGHT][WIDTH];
string userinputprompt, filename;
userinputprompt = "Data Filename: ";
cout<<userinputprompt<<endl;
getline(cin,filename);
ifstream inputfile;
inputfile.open(filename.c_str());
for(int i=0; i<HEIGHT; i++)
{
for(int j=0; j<WIDTH; j++)
{
/*if(!(inputfile>>array_req[i][j]))
{
cerr<<"Error";
break;
}
else if(!inputfile) // its error.. , can use a cerr here...
{
cerr<<"Error";
break;
}
else*/
inputfile>>array_req[i][j];
cout<<i<<","<<j<<"-->"<<array_req[i][j]<<endl;
}
/* This is not needed, read above comment
else
{
inputfile >> array_req[i][j];
}*/
}
for(int p=0; p<HEIGHT; p++)
{
for(int q=0; q<WIDTH; q++)
{
cout<<array_req[p][q]<<" ";
}
cout<<"\n";
}
inputfile.close();
getchar();
return 0;
}
。 编辑的代码 - 输出数组是一个空矩阵。请帮忙。代码中有什么问题..正确编译。根据我在此处阅读的大量示例,尝试使用 getline 和 stringstream 逐行读取..仍然无法正常工作。
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include <sstream>
#include <stdlib.h>
const int HEIGHT = 3;
const int WIDTH = 4;
const int BUFFSIZE = 10000;
using namespace std;
int main(){
int array_req [HEIGHT][WIDTH];
char buff[BUFFSIZE];
string userinputprompt, filename;
userinputprompt = "COLORDATA FILENAME: ";
cout<<userinputprompt<<endl;
getline(cin,filename);
ifstream inputfile;
stringstream ss;
inputfile.open(filename.c_str());
for (int i=0; i<HEIGHT; i++)
{
inputfile.getline(buff,BUFFSIZE,'\n');
ss<<buff;
for(int j=0;j<WIDTH; j++)
{
ss.getline(buff,1000,'\n');
array_req[i][j]=atoi(buff);
}
ss<<"";
ss.clear();
}
for(int p=0; p<HEIGHT; p++)
{
for(int q=0; q<WIDTH; q++)
{
cout<<array_req[p][q]<<" ";
}
cout<<"\n";
}
inputfile.close();
getchar();
return 0;
}
【问题讨论】:
-
也许您需要使用 F-10 键对其进行调试,以查看每一行代码到底发生了什么?
-
@FirstStep 感谢您如此迅速地恢复...代码是否正确? ..你如何标记某人..这是我第一次在这个网站上..O.o oops!
-
如果已编译,则代码正确(无语法错误)。但是,问题可能出在变量和对象的值(逻辑错误)中。找到它的唯一方法是通过 Step(ping)-在您的代码上,使用 F-10 键逐个语句,同时检查途中每个变量的值
-
@FirstStep 呃 F-10 键?那不是IDE特定的吗?如果他从命令行执行呢?
-
@mwm314 如果我假设 VS 因为他没有提到呢?
标签: c++ arrays file text import