从 stdin 读取并将值存储到数组 C++
可能的重复:
如何将二维字符数组转换为二维 int 数组?
我正在尝试从 stdin 读取输入,并在遇到 EOF
时停止读取。我需要将这些值作为整数存储在 2x2 数组 array[i][j]
中。
我正在从单行读取 81 个数独字符(整数)+ 2 个字符(\n
和 EOF
),总共 83 个。
例如:
标准输入——> 123414292142341......2\n
如何只存储每个array[i][j]
中的数字?当我遇到
时停止读入?
因此,每 9 个整数之后,我需要增加 j 以获得下一行。
我想用 C++ 来做这个,
谢谢!
到目前为止我已经尝试过
// 以 83 个字符的单行读取(81 个数独整数 + \n 和 //将每个整数存储到相应行和列的数组中
#include iostream
using namespace std;
string input_line;
int main()
{
while(cin) {
getline(cin, input_line);
};
return 0;
}
如何将字符串“input_line”标记为整数字符?然后到atoi转成int,最后存到数独数组中??
好的,谢谢,快完成了。但我现在不断收到从“char”到“const char*”的无效转换错误!
#include <iostream>
#include <stdlib.h>
using namespace std;
string input_line;
int main()
{
char buffer[9][9];
int sudoku[9][9];
int v;
cout << "Enter input: " << endl;
cin >> (char*)buffer;
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
v = atoi(buffer[i][j]);
sudoku[i][j] = v;
Possible Duplicate:
How to convert a 2d char array to a 2d int array?
I'm trying to read input from stdin and stop reading when encountering EOF
. I need to store these values as integers in a 2x2 array, array[i][j]
.
I'm reading in 81 Sudoku characters (integers) from a single line + 2 more characters (\n
and EOF
) for a total of 83.
Ex:
STDIN -- > 123414292142341......2\n <EOF>
How do I only store the numbers in each array[i][j]
? and stop reading in when I encounter an <EOF>
?
So, after every 9 ints, I need to increment j to get the next row.
I'm looking to do this in C++
Thanks!
I have tried this so far
//Read in single line of 83 characters (81 sudoku integers + \n and
//Store each integer into array of corresponding row and column
#include iostream
using namespace std;
string input_line;
int main()
{
while(cin) {
getline(cin, input_line);
};
return 0;
}
How do I tokenize the string "input_line" into a character of integers? and then to atoi to convert to int, and then finally store them in the Sudoku array??
OK, thanks almost done. but I now keep getting an invalid conversion from 'char' to 'const char*' error!
#include <iostream>
#include <stdlib.h>
using namespace std;
string input_line;
int main()
{
char buffer[9][9];
int sudoku[9][9];
int v;
cout << "Enter input: " << endl;
cin >> (char*)buffer;
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
v = atoi(buffer[i][j]);
sudoku[i][j] = v;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想要使用 C++,那么您可以选择使用 C++ 风格
cin
。以下是伪代码:这里我们利用了任何数字都小于
的事实。 256.
.因此,您的表格将自动排列在数独[][]
内。If you want in C++ then you may choose to use C++ style
cin
. Following is pseudo code:Here we are taking advantage of the fact that any digit will be less than
< 256
. So your table will be arranged inside thesudoku[][]
automatically.