gpt4 book ai didi

c++ - 当我将数组声明为 3 时,为什么我的数组只接受 2 个值?

转载 作者:行者123 更新时间:2023-12-01 14:48:09 24 4
gpt4 key购买 nike

这是我的代码:

    int amount;
cout<<"How many books are you donating? ";
cin>>amount;
string donation[amount];

cout<<"Enter the titles:"<<endl;
for (int i=0; i<amount; i+=1)
{
getline(cin.ignore(numeric_limits<streamsize>::max(), '\n'), donation[i]);
}

cout<<endl<<"You donated these:";
for (int j=0; j<amount; j+=1)
{
cout<<donation[j]<<endl;
}

即使我只为 amount 输入 3 个值,这也接受 5 个值.然后它只打印值 1、3 和 5。

如果我把它写成 getline(cin.ignore(), donation[i]);getline(cin.ignore(1, '\n'), donation[i]); ,那么输出变成这样:
How many books are you donating? 3
Enter the titles:
book1
book2
book3

You donated these:
book1
ook2
ook3

我应该在 cin.ignore()中写什么让它忽略 \n值(value)?

最佳答案

您需要在第一个 cin>>amount 读取后丢弃\n,

注意:你可以使用 i++ 或++i 而不是 i+=1 (这是一种更标准的方式)

#include <iostream>
#include <string>
#include <limits>

using namespace std;

int main()
{
int amount;
cout<<"How many books are you donating? ";
cin>>amount;
string donation[amount];
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');

cout<<"Enter the titles:"<<endl;
for (int i=0; i<amount; i++)
{
cout<< "Enter title "<<i << ":";
getline(cin, donation[i]);
}

cout<<endl<<"You donated these:"<<endl;
for (int j=0; j<amount; j++)
{
cout<<donation[j]<<endl;
}

return 0;
}

关于c++ - 当我将数组声明为 3 时,为什么我的数组只接受 2 个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61243326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com