c++ - C++中的混合数据类型输入

标签 c++

为什么这个程序可以正常运行?

#include<iostream>
using namespace std;
int main()
{
    cout <<"What year was your house built?\n";
    int year;
    cin >> year;
    cout << "What is its street address?\n";
    char address[80];
    cin>>address;
    cout << "Year built: " << year << endl;
    cout << "Address: " << address << endl;
    cout << "Done!\n";
    return 0;
}

为什么这个程序不提供输入地址的机会?

#include <iostream>
int main()
{
    using namespace std;
    cout <<"What year was your house built?\n";
    int year;
    cin >> year;
    cout << "What is its street address?\n";
    char address[80];
    cin.getline(address, 80);
    cout << "Year built: " << year << endl;
    cout << "Address: " << address << endl;
    cout << "Done!\n";
    return 0;
}

最佳答案

cin>> 在 iostream 中留下换行符 (\n)。如果在 cin>> 之后使用 getlinegetline 将这个换行符视为前导空格,认为它已完成并停止进一步读取。

解决问题的两种方法:

避免将 getline 放在 cin >> 之后

在调用 getline 之前,通过“抓取”它并将其放入“虚拟”变量中,使用 cin>> 中的尾随换行符。

string dummy;
getline(cin, dummy);

为什么第一个程序有效而第二个程序无效?

第一个程序:
cin 语句使用输入的年份并将 \n 作为垃圾留在流中。 cin 语句不会读取(或“抓取”)\ncin 在读取数据时忽略 \n。所以程序1中的cin可以正常读取数据。

第二个程序:
getline,读取并抓取\n。因此,当它看到 cin 中遗漏的\n 时,它会获取 \n 并认为它已完成读取,从而导致第二个程序无法按预期运行。

关于c++ - C++中的混合数据类型输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6799707/

相关文章:

c++ - 使用 boost async_read 和 posix::stream_descriptor 从键盘读取

c++ - 模板对象声明和初始化: manually call template constructor to bypass standard constructors calls order

c++ - C++ 中的 4d 映射?

c++ - 如何在我的 Ubuntu 11.04 (Natty Narwhal) 上安装 g++/gcc 4.6?

c++ - 破译 MSDN C++ API 调用和结构以及从 VB6 调用

c++ - 有谁用过Posix pthread win32库,dll文件

c++ - 使用包含给定空格的路径启动程序

C++11 auto、std::function 和对重载函数的模糊调用

c++ - 地址 sanitizer 在静态转换无效指针时报告错误

C++ 加倍 : dividing by 100 causes very small error