2014-01-19 55 views
0

我有一个字符串,其中包含任意数量的数字的任意数量的整数,我需要将每个整数解析为以前分配的程序矩阵的一个元素。出于某种原因,输出被复制字符串的最后一个数字时,给出一个新的字符串,就像这样:解析字符串导致重复值

的data.txt

1 4 5 6 8 
5 5 5 5 5 
3 3 3 3 3 
1 1 1 1 1 

程序输出:

1 4 5 6 5 
5 5 5 5 3 
3 3 3 3 1 
1 1 1 1 1 

我可以看到每行的最后一个元素被下一行的第一个元素覆盖,但我不知道为什么它正在这样做。下面是相关的代码:

while(getline(inFile, readIn)) { 
     parse(readIn, mtrx, r); 
     r++; 
    } 

//...... 

void parse(string str, matrix& mtrx, int r) 
{ 
    string value = ""; 
    str.append("*"); 
    int i=0;      //finds integers in string 
    int c=0;      //place holders for columns 
    while(i < str.length()) { 
     value = ""; 
     while(str[i] != ' ' && str[i] != '*') { 
      value += str[i]; 
      i++; 
     } 
     mtrx.set(r,c, atoi(value.c_str())); 
     c++; 
     i++; 
    } 
} 
+0

编译所有警告和调试信息(例如'g ++ -Wall -g')。学习如何使用调试器(例如'gdb')。对于任意大的数字,请考虑使用[bignum](http://en.wikipedia.org/wiki/Bignum)库,如[GMPlib](http://gmplib.org/) –

+1

一些提示:使用矢量载体,阅读['std :: istringstream'](http://en.cppreference.com/w/cpp/io/basic_istringstream),['std :: copy'](http://en.cppreference.com/ w/cpp/algorithm/copy),['std :: istream_iterator'](http://en.cppreference.com/w/cpp/iterator/istream_iterator)和['std :: back_inserter'](http:// en.cppreference.com/w/cpp/iterator/back_inserter)。使用它,这样做其实很简单。 –

+0

当你知道长度是多少时,为什么要添加'*'? – kfsone

回答

2

看起来你MTRX仅仅是4×4的元素,因为在C++中默认没有数组边界测试,所以你可以阅读登天。当写入一行的最后一个元素时,可以写入下一行的第一个元素,写入下一行时将覆盖它。当读取一行的最后一个元素时,读取下一行的第一个元素。最后一行的最后一个元素是可以的,因为你写的超出了数组本身并且读回来了,但是这会导致一些有趣的其他问题。