【问题标题】:C++ Why is my first data input with getline(cin, array[x]) is on the sameline and broken while my 2nd data input is fine? [duplicate]C++ 为什么我的第一个数据输入与 getline(cin, array[x]) 在同一行并且损坏,而我的第二个数据输入很好? [复制]
【发布时间】:2021-01-03 17:07:08
【问题描述】:
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    int person;
    cout << "How many person to data: ";
    cin  >> person;

    int x = 0;
    int i = 1;
    string name[person];
    string adress[person];

    while(x < person){
        cout << i << " person data" << endl;
        cout << "Name: ";
        getline(cin, name[x]);
        cout << "Adress: ";
        getline(cin, adress[x]);
        cout << endl;
        x++, i++;
    }

    for(x=0; x<person; x++){
        cout << name[x] << setw(15) << adress[x] << endl;
    }
}

这是我将名称和地址存储到数组 name[] 和 adress[] 中的代码 然后我用for循环打印他们的名字和地址

这是输出图像 Result

为什么我的 1 个人数据损坏了? 姓名和地址在同一行,而我的第二个人数据没问题?

如果我使用 cin 很好 >> 但我使用 getline 所以我可以使用全名和带空格的地址

【问题讨论】:

    标签: c++ arrays string vector getline


    【解决方案1】:

    对于初学者可变长度数组

    string name[person];
    string adress[person];
    

    不是标准的 C++ 功能。而是使用标准容器std::vector&lt;std::string&gt; 之类的

    #include <vector>
    
    //...
    
    std::vector<std::string> name( person );
    std::vector<std::string> adress( person );
    

    或者,您可以声明std::pair&lt;std::string, std::string&gt; 类型的对象向量,而不是两个向量

    #include <utility>
    #include <vector>
    
    //...
    
    std::vector<std::pair<std::string, std::string>> persons( person );
    

    在这种情况下,您应该像这样在循环中编写

        //...
        getline(cin, persons[x].first );
        //...
        getline(cin, persons[x].second);
    

    输入后

    cin  >> person;
    

    输入流包含与按下的 Enter 键对应的换行符 '\n'。您需要在 while 循环之前将其删除,例如

    std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
    

    为此,您需要包含标题&lt;limits&gt;

    【讨论】:

    • 还可以考虑将名称和地址聚合到一个结构中,然后在该结构中创建一个 std::vector。这通常有助于减少记账开销。
    猜你喜欢
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 2015-07-08
    • 2019-08-22
    • 2021-07-26
    • 2021-08-17
    • 2019-08-11
    • 2021-06-05
    相关资源
    最近更新 更多