大数字,输入字符[]

Big Number,input char[]

本文关键字:字符 输入 数字      更新时间:2023-10-16

我对以下代码有问题:

#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;

此示例代码将简单地读取一行并在标准输出中逐字输出它。