我正在嘗試編寫一個C++程序來讀取包含數據(122X300矩陣 - 製表符分隔的矩陣)的txt文件並將其顯示出來。以下是我在廣泛引用谷歌和本網站上的許多類似問題後所寫的代碼。在運行代碼時,我沒有遇到任何錯誤,但是它確實給了我大量的數字列表,這些數字我無法理解。以下是代碼:任何幫助都會很棒。我不知道我哪裏錯了。謝謝。沒有得到我想要的輸出
DID通過@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;
}
。 EDITED代碼 - 輸出數組是一個空矩陣。請幫忙。代碼..compiles中存在什麼錯誤。嘗試使用getline和stringstream逐行讀取基於很多例子,我在這裏閱讀..still不工作。
#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! – fattypanda
如果編譯,則代碼是正確的(無語法錯誤)。但是,問題可能在於變量和對象的值(邏輯錯誤)。找到它的唯一方法是通過Step(ping) - 在您的代碼中,使用F-10鍵聲明語句,同時檢查您路上每個變量的值 –