大数字,输入字符[]
Big Number,input char[]
我对以下代码有问题:
#include<iostream>
using namespace std;
int main()
{
char a[200];
int i;
for (i = 0; cin.get() != 'n'; i++) {
cin >> a[i];
}
cout << i;
system("pause");
return 0;
}
例如,我不知道为什么当我输入没有空格 10 个字符时。 i si 等于 10/2=5 ?
你丢弃每个奇数符号,cin.get()
读取符号 1, cin >>
读取符号2,再次cin.get()
读取符号3,cin >>
从标准输入中读取符号 4。
你扔掉了一半的cin
结果。
当您使用 cin
时,会读取一个字符,但您不会将其分配给 for
循环条件中的任何内容;只有在循环主体内部才能保存它。
中,您读入另一个字符(在循环测试条件期间已经读入的字符之后(并分配该字符。循环重复,下一个字符读取再次被丢弃,并带有行cin.get() != 'n'
,因为您没有将结果分配给任何内容。这种情况仍在继续,您丢弃的字符与您"保存"到数组中的字符交替出现。
你会得到两个字符,一个递增 i 变量,只有第二个插入数组
int main()
{
char a[200];
int i;
\ cin.get() - get one char and insert it in a[i]
\ after that, compare this value with 'n'
\ if equal, break the loop, if different, continue
for (i = 0; (a[i] = cin.get()) != 'n'; i++);
\ last character ('n') should be replaced with ' '
a[i]=' ';
cout << i;
system("pause");
return 0;
}
而解决方案:
int main()
{
char a[200];
int i=0;
cin >> a[i];
while (a[i] != 'n')
{
i++;
cin >> a[i];
}
a[i]=' ';
cout << i;
system("pause");
return 0;
}
做 - 同时解决方案:
int main()
{
char a[200];
int i=0;
do
{
cin >> a[i];
}
while(a[i++]!='n');
a[i-1]=' ';
cout << i-1;
system("pause");
return 0;
}
事实上,您正在以两种不同的方式读取标准输入(std::cin
(,每两个字符提取仅存储一次其输出。
std::basic_istream::get
(cin.get()
( 从流中提取一个或多个字符。一旦提取,乳清就会被遗忘,被送往边缘。你只是忽略它们。这不是我怀疑你想做的。
std::basic_istream::operator>>
(cin >> ...
(也提取字符(遵循右侧操作数的类型(。
因此,输入十个字符时,您在for
条件检查中忽略其中的五个字符,并将五个字符存储在循环块中。
读取字符的正确方法是使用std::getline
(en.cppreference.com/w/cpp/string/basic_string/getline(:
std::string input;
std::getline(cin, input);
std::cout << input << std::endl;
此示例代码将简单地读取一行并在标准输出中逐字输出它。
- 如何忽略第一个字符输入后的所有内容
- 使用单个变量对字符输入进行计数
- 确定用户字符输入 C++ 的结束
- 将单个字符串/字符输入串行监视器
- 如何将字符输入限制为仅获取一个字符串"cin"
- C++:使用 fgets() 读取字符输入时出错
- 如何拒绝 cin 中的字符输入并定义最小和最大整数值
- C++ 字符输入仅输出第一个字母
- 限制 2D 数组中的字符输入
- 循环直到整数输入在所需范围内无法处理非数字字符输入
- C++常量字符*输入
- 使用带符号字符输入的isalnum-Visual C++
- 限制C++中的字符输入
- 字符输入问题
- 字符** + 输入" "字符
- 文件 I/O 操作 - 奇怪的字符输入
- 如何在不暂停循环的情况下使用字符输入停止循环
- C++ - 对'if'语句使用特定字符输入
- 使用 "NEW" 获取字符输入和给定输出,并从用户那里获取字符串长度
- 正确的逐个字符输入