我需要从用户那里读取数字1000101
并保存在一个数组中。
例如 :
int array1 [6]={1,0,0,1,0,1};
但我需要用户在一行中输入数字。知道如何将用户的一个长数字保存在数组中吗?
我需要从用户那里读取数字1000101
并保存在一个数组中。
例如 :
int array1 [6]={1,0,0,1,0,1};
但我需要用户在一行中输入数字。知道如何将用户的一个长数字保存在数组中吗?
您可以从std::cin
例如std::getline
. 获得该行后,一次获取一个字符并检查它是 1 还是 0,然后将其转换为整数并将其添加到数组中。
请记住检查字符串和数组的限制,以免超出范围。
char c;
std::vector<int> number;
while (std::cin >> c)
if (c == '0' || c == '1')
number.push_back(c - '0');
else if (c == '\n')
break;
else
throw std::runtime_error("illegal characters in number");