鱼C论坛

 找回密码
 立即注册
查看: 1313|回复: 2

萌新求助## while循环##为什么不能到达预期的效果

[复制链接]
发表于 2021-10-12 11:39:56 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
源码如下:
#include <string>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
        int i;
        vector <int > v1;
        while (cin >> i  )
        {
                v1.push_back(i);
        }
        for (auto n : v1)
        {
                cout << n << endl;
        }
        return 0;
}

当我使用VS 2019运行这段代码时,每次我输入几个整数再敲回车程序都不会响应,只有当我输入非int值,比如一个char值的's'时,程序才会继续响应。合理怀疑问题出在while循环的条件上,但不知道该怎么改进。55555求助各位大佬

                               
登录/注册后可看大图



想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-10-12 11:57:20 | 显示全部楼层
本帖最后由 hrpzcf 于 2021-10-12 12:01 编辑

因为你的while循环的停止条件就是输入非int类型数据

int i;
while (cin >> i) //就是这里,当输入符合int类型的字符时cin成功,while循环就继续;输入不符合int类型的字符时cin失败退出。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-10-12 12:11:38 | 显示全部楼层
#include <iostream>
#include <vector>
#include <sstream>

int main(){
    std::vector<int> myVector;
    std::string line;
    std::getline(std::cin, line);
    std::istringstream os(line);
    
    int i;
    
    while(os >> i) myVector.push_back(i);
    for (auto n : myVector) std::cout << n << std::endl;
    return 0;
}
13 7 18 9 5 74
13
7
18
9
5
74
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-22 15:47

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表