我正在尝试将 9 个字符的字符串读入 9 个整数值,然后存储在一个数组中(现在我将它们存储在 9 个单独的整数中,一旦它们读取成功,就会将它们放入数组中)。我采用的一般方法:con 字符串,将其拆分为 9 个字符值,将(atoi)每个转换为整数并存储为 9 个整数,将整数放入数组中。奇怪的是,虽然单个值被毫无问题地拆分为单个字符,但在某种程度上“看到”其他相邻值(根本不包含在该字符中!)并将它们向后转换。
示例代码:
countrows = 1;
countcols = 1;
cout << endl << "Enter values for boxes in row " << countrows << ", enter 0 for open boxes (enter 9 numbers, with no spaces or delimiters): ";
string inputline;
cin >> inputline;
char col1, col2, col3, col4, col5, col6, col7, col8, col9;
int int1, int2, int3, int4, int5, int6, int7, int8, int9;
col1 = inputline[0];
col2 = inputline[1];
col3 = inputline[2];
col4 = inputline[3];
col5 = inputline[4];
col6 = inputline[5];
col7 = inputline[6];
col8 = inputline[7];
col9 = inputline[8];
int1 = atoi(&col1);
int2 = atoi(&col2);
int3 = atoi(&col3);
int4 = atoi(&col4);
int5 = atoi(&col5);
int6 = atoi(&col6);
int7 = atoi(&col7);
int8 = atoi(&col8);
int9 = atoi(&col9);
cout << "inputline: " << inputline << endl;
cout << "col1: " << col1 << " col2: " << col2 << " col3: " << col3 << endl; //debug line
cout << "int1: " << int1 << " int2: " << int2 << " int3: " << int3 << endl; //debug line
结果是:
在第 1 行输入框的值,为打开的框输入 0(输入 9 个数字,没有空格或分隔符):456123789 输入行:456123789 col1:4 col2:5 col3:6 int1:4 int2:54 int3:654
为什么int包含5和int3 65(应该是int1:4 int2:5 int3:6)