【问题标题】:stopping when user enters the 'enter' key当用户输入“输入”键时停止
【发布时间】:2017-04-09 06:17:48
【问题描述】:

我一直在编写一个程序,它以两个不同的“向量”从用户那里获取输入,并在按下回车键时停止。代码如下

 #include <iostream>
 #include <vector>
 #include <string>

using namespace std;

int main()
{
    vector<string> a,c;
    string b;
    int m=0;//,words = 0;
    do
    {
        cin>>a[m];
        m++;
    }
    while(cin.get()!= '\n');

    int n=0;
    do
    {
        cin>>c[n];
        n++;
    }
    while(cin.get() != '\n');

    int mida=a.size()/2, midc=c.size()/2;
    int count;
    int i,j;

    for(i=0;i<n;i++)
        for(j=0;j<m;j++)
            {
                if(a[i] == c[j])
                count++;
            }

    if(count >= mida  || count >= midc)
        cout<<"similar"<<endl;
    else
        cout<<"dissimilar"<<endl;
    return 0;
}

现在的问题是,当我在输入单词后运行代码时,我需要在向量中放入类似“芒果”“橙色”的东西,用空格分隔,但是 我一按 Enter,就会出现分段错误。谁能告诉我可能出了什么问题。

【问题讨论】:

    标签: c++ string vector segmentation-fault


    【解决方案1】:

    当您创建一个std::vector 对象时,它一开始是,它的size 将为零,并且其中的所有索引都将超出范围并导致未定义的行为(以及可能的崩溃)。

    您可以使用push_back 将元素附加到向量。喜欢

    std::string s;
    std::cin >> s;
    a.push_back(s);
    

    虽然以上是您遇到崩溃的最可能原因,但这不是您唯一的问题。另一个是每个输入字符串都可能以换行符结束。如果你想读一整行,然后把它分成“单词”,那么我建议你使用std::getline来读整行,然后使用std::istringstream从行中获取单独的单词。

    您还可以使用std::istream_iterator 轻松地将append 字符串从输入流转换为向量。

    你可以这样做

    std::string line;
    std::getline(std::cin, line);
    std::istringstream iss(line);
    
    a = std::vector<std::string>(std::istream_iterator<std::string>(iss),
                    std::string>(std::istream_iterator<std::string>());
    

    【讨论】:

      【解决方案2】:

      cin&gt;&gt;a[m];

      您正在索引向量 a 的末尾。因为没有给向量指定大小,所以它甚至没有空间来分配a[0]

      一种可能的解决方案是使用临时变量来获取用户输入,然后使用a.push_back[input]

      【讨论】:

      • 试试(不是)。同上
      猜你喜欢
      • 2020-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      • 2019-08-25
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多