将一行数据输入到布尔数组
Input data in one line to array of bool
是否可以在一行中以正确的方式将数据键入布尔数组?
我有这样的东西:
#include <iostream>
using namespace std;
int main() {
unsigned short a;
cin >> a;
bool *b = new bool[a];
for(int i = 0; i < a; ++i)
cin >> b[i];
for(int i = 0; i < a; ++i)
cout << b[i];
delete [] b;
return 0;
}
例如:
正确输入:
5
1
0
1
0
1
正确输出:
10101
但我想这样:
输入:
5
10101
输出:
10101
您可以将整个输入读入一个字符串,然后将“1”和“0”char
转换为bool
:
#include <iostream>
#include <string>
int main()
{
std::string input;
std::cin >> input;
std::cout << "Input length was: " << input.length() << std::endl;
std::cout << "Output: ";
for (auto c : input)
{
std::cout << static_cast<bool>(c - '0');
}
return 0;
}
您可以从输入中读取字符并将其转换为布尔值,例如:
for(int i = 0; i < a; ++i) {
char c;
cin >> c;
b[i] = static_cast<bool>(c - '0');
}
注意:这将允许输入单行和多行,因为 cin 忽略空白字符。
是否可以在一行中以正确的方式将数据键入布尔数组? 我有这样的东西:
#include <iostream>
using namespace std;
int main() {
unsigned short a;
cin >> a;
bool *b = new bool[a];
for(int i = 0; i < a; ++i)
cin >> b[i];
for(int i = 0; i < a; ++i)
cout << b[i];
delete [] b;
return 0;
}
例如:
正确输入:
5
1
0
1
0
1
正确输出:
10101
但我想这样:
输入:
5
10101
输出:
10101
您可以将整个输入读入一个字符串,然后将“1”和“0”char
转换为bool
:
#include <iostream>
#include <string>
int main()
{
std::string input;
std::cin >> input;
std::cout << "Input length was: " << input.length() << std::endl;
std::cout << "Output: ";
for (auto c : input)
{
std::cout << static_cast<bool>(c - '0');
}
return 0;
}
您可以从输入中读取字符并将其转换为布尔值,例如:
for(int i = 0; i < a; ++i) {
char c;
cin >> c;
b[i] = static_cast<bool>(c - '0');
}
注意:这将允许输入单行和多行,因为 cin 忽略空白字符。