cin操作员链接以简化系统输出



下午好,

我有一些代码要求用户输入一个数字来获得一些多项式值。第一个数字是希望输入的多项式的数量(int N(,下面的数字是指向链表中的值的指针,并以系数(int&coe(和幂(int&aamp;pow(的集合输入。

当我运行程序时,它每次都会提示用户输入必要的值。但是,如果一次输入所有值,它将输出N次提示。有没有一种方法可以让我设置一个控件来识别我有多少输入,然后在计算值之前正确输出所需的提示数量?

例如,如果我输入3,它需要3组数字,并且我可以一次一组,或者一次全部输入/如果我输入4 9 3 0 5 7,那么它将跳过"0";输入"消息并继续。同样,如果我为多项式请求输入5,并输入5 8 5 3 7 6 4,它将只打印一次消息,在继续执行程序之前还有两组。

代码:

int N = 0;
printf("Enter N polynomials: ");
cin >>N;
Node *node = NULL;
int pow, coe;
for (int i = 0; i < N; ++i)
{
printf("Enter coeff. & pow. of poly.: term %d separated by " ": ", i);
cin >> coe >> pow;
createNode(coe, pow, &node);
}

使用std::getline()将用户输入读取到std::string中,然后使用std::istringstream从该字符串中读取整数,直到没有整数为止,然后返回std::cin并根据需要提示输入更多整数。

int N = 0;
cout << “Enter N polynomials: ";
cin >> N;
string input;
getline(cin, input);
istringstream iss(input);
Node *node = NULL;
int pow, coe;
for (int i = 0; i < N; ++i)
{
if (!(iss >> coe >> pow))
{
cout << “Enter coeff. & pow. of poly.: term “ << i << ” separated by " ": ";
cin >> coe >> pow;
}
createNode(coe, pow, &node);
}

最新更新