cin 仅在 while 循环内运行一次

问题描述 投票:0回答:4

我看过另一篇标题几乎相同的帖子,但它根本没有帮助,因为他们的代码中有错误。我只想获取客户端输入的值并添加它们,但它只需要第一个输入

#include <iostream>
#include <string>
using namespace std;

int issa_def() {
    int issa[] = {};
    int half_ans_issa[] = {};
    int i  = 0;
    int cn = 0;
    while(true) {
        cout << "enter prices of items ordered by issa: ";
        cin >> cn;
        if(cn == 111) {
            break;
        }
        else {
        issa[i] = cn;
        }
        i++;
        cin.clear();
    }
    int a = 0;
    for(int i = 0;i <= sizeof(issa);i+=2) {
        int ans = issa[i] + issa[i+1];
        half_ans_issa[a] = ans;
        a++;
        cout << issa[i] << "\n" << issa[i+1] << "\n";
    }
    a = 0;
    cout << half_ans_issa[a];
}
int main() {
    issa_def();

}

这是打印我输入的第一个和第二个输入的值以及总和后的输出

C:\Users\akram\Documents\code>a.exe
enter prices of items ordered by issa: 5
enter prices of items ordered by issa: 5
enter prices of items ordered by issa: 111
first input:5
second input:0
output:5

注意:111 是退出代码

我按照用户 –πάντα ῥεῖ 的说明打开了编译器警告,并且收到了错误

dahra.cpp:23:18: warning: comparison between signed and unsigned integer express
ions [-Wsign-compare]
  for(int i = 0;i <= sizeof(issa);i+=2)
c++ while-loop cin
4个回答
1
投票

您的数组的大小是多少?您使用

{}
初始化它们,因此它们只是一个
int*
,没有任何内存分配。一旦你向
issa[i]
插入值,你就会溢出。

出于类似的原因,您无法从 0 迭代到

sizeof(issa)
(包括后者)。首先,
sizeof
给出的是字节大小,而不是数组元素的数量。其次,如果
sizeof
按您的预期工作,您将迭代 (n+1) 个元素,而不是 (n) 个元素。最后,如果数组有奇数个元素,则可以访问数组外部的内存 (
issa[i+1]
)。您应该使用
std::vector
来获取任意数量的输入。

最后,您应该有一个

return
issa_def
函数。

总结一下,当您在数组中插入元素时,您应该使用

issa.push_back(cn)

并且,在迭代

issa
时,您应该考虑偶数/奇数数组,以及数组的适当大小:

for(int i = 0; i < issa.size() - 1; i += 2) {
  ...
}

0
投票

您应该用 cin.clear(); cin.ignore();

 刷新 
cin

缓冲区

cin.clear()
清除流的内部状态,这样可以避免错误。然后
cin.ignore()
忽略一切,直到下一行(这就是你想要的)


0
投票

首先,您必须定义具有恒定大小的数组issa。这里您定义了一个空数组。因此,您无法使用 issa[i] 访问元素并分配新值。为此,您可以使用向量数组。

vector<int> issa;
int temp;
cin>>temp;
issa.push_back(temp);

第二你必须写一个退货声明。

警告:有符号和无符号之间的比较

在这里,您的代码的问题是您正在将有符号整数与无符号整数进行比较。 sizeof(issa) 返回一个无符号整数。

你可以通过声明一个有符号整数来解决这个问题

int n = sizeof(issa);
for(int i = 0;i <n ;i+=2) {


0
投票

Все работает,спасибо orgромное!

© www.soinside.com 2019 - 2024. All rights reserved.