求助:从文本读入数据,但运行结果有问题

Infinity09_run08 2011-10-18 08:29:36
#include<iostream>
#include<cstdlib>
#include<string>
#include<cstring>
#include<fstream>
#include<cassert>
using namespace std;
int main()
{
ifstream infile;
infile.open("data.txt");
assert(infile.is_open());

int Sodu[9][9]={0},i=0,j=0,k=0;
string line;
while(infile)
{
char cline[22]={0};
getline(infile,line);

strcpy(cline,line.c_str());
for(k=0;k<strlen(cline);++k)
{
if(cline[k]==' ')continue;
else
{Sodu[i][j]=cline[k]-'0';cout<<Sodu[i][j++]<<" ";}
}
++i;
j=0;
cout<<endl;
}

for(i=0;i<9;++i)
{
for(j=0;j<9;++j)

cout<<Sodu[i][j]<<" ";
cout<<endl;
}
system("pause");
return 0;
}
/*data.txt中的内容:
2 3 6 5 9 7 1 4 8
5 7 8 3 1 4 2 9 6
9 1 4 6 2 8 5 7 3
8 9 5 7 4 2 3 6 1
6 4 7 1 8 3 9 5 2
3 2 1 9 5 6 4 8 7
1 8 9 2 7 5 6 3 4
4 6 2 8 3 9 7 1 5
7 5 3 4 6 1 8 2 9
*/当上面数阵只要少于九行时就可以。
为什么有九行时输出结果会多一行,会重复输出第九行。
...全文
74 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
程序员小迷 2012-02-09
  • 打赏
  • 举报
回复
一点问题也没有啊
xcode gcc4.2 ok
楼主什么编译器
Phoenix Slade 2011-10-23
  • 打赏
  • 举报
回复
用结束标志啊
while(!infile.eof())
{
....
}
haoshenwang 2011-10-23
  • 打赏
  • 举报
回复
应该和文件结束标志有关吧
赵4老师 2011-10-19
  • 打赏
  • 举报
回复
“多一少一”问题占程序员常犯错误的10%以上!
gfy5216 2011-10-19
  • 打赏
  • 举报
回复
重复输出的时候应该不是原样的第九行吧。
问题出在for(k=0;k<strlen(cline);++k)
{
if(cline[k]==' ')continue;
else
{Sodu[i][j]=cline[k]-'0';cout<<Sodu[i][j++]<<" ";} }
Infinity09_run08 2011-10-19
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 gfy5216 的回复:]
重复输出的时候应该不是原样的第九行吧。
问题出在for(k=0;k<strlen(cline);++k)
{
if(cline[k]==' ')continue;
else
{Sodu[i][j]=cline[k]-'0';cout<<Sodu[i][j++]<<" ";} }
[/Quote]
重复输出的时候确实是指重复最后一行。但是当如果从data.txt中的读入的数据只要少几行,输出都没有问题。
Infinity09_run08 2011-10-19
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 gfy5216 的回复:]
重复输出的时候应该不是原样的第九行吧。
而且在把data.txt的行数减少都不会出现重复最后一行的情况。
问题出在for(k=0;k<strlen(cline);++k)
{
if(cline[k]==' ')continue;
else
{Sodu[i][j]=cline[k]-'0';cout<<Sodu[i][j++]<<" ";} }
[/Quote]
问题感觉在这里,但是不知道怎么改。

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧