gpt4 book ai didi

c++ - cin 对象 - C++

转载 作者:行者123 更新时间:2023-11-28 03:33:05 29 4
gpt4 key购买 nike

   #include <iostream>
using namespace std;

struct list
{
int data;
list *next;
};

list *node, *tail = NULL, *head = NULL;
void add2list();
void extrem();

int main()
{
add2list();
extrem();

return 0;
}

void add2list()
{
int input;
cout << "Adding values to list :\n";
cout << ">>";

while(cin >> input)
{
node = new list;
node->data = input;
node->next = NULL;

if (head == NULL)
{
head = node;
tail = node;
}
else
{
tail->next = node;
tail = node;
}
cout << ">>";
}
}

void extrem()
{
int x, y;
cin >> x >> y;
}

当我运行这个程序时,它只执行 add2list 函数????

我添加了cin.clear(),但是问题没有解决,为什么??

有些人可以清楚地解释我该如何解决这个问题

以及什么时候使用 cin.clear() 对象有用🙟

对不起 4 我的英语不好

最佳答案

你的逻辑被破坏了:cin >> inputcin >> x >> y 都试图从流中提取 int .当 add2list 中的 while 循环中断时,不再可能从流中提取 int。重置错误标志不会突然使可解析数据出现在流中。当您尝试读入 x 时,您将再次失败,原因与您从循环中中断的原因相同。

您需要找到一种更好的方法来读取输入的不同部分,即一个用于构建列表,另一个用于读取更多数据。一个基于 line 的通用方法(通过 std::getline)可能是一个好的开始,您可以实现一个简单的 shell,它接受“创建列表”等命令。

关于c++ - cin 对象 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11979065/

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