【问题标题】:How can I run through a while loop until a new line is reached?如何运行 while 循环直到到达新行?
【发布时间】:2017-07-19 19:07:42
【问题描述】:

我需要将通过 std::cin 传入的单词设置为字符向量,直到到达换行符 ('\n') 字符。 这是我到目前为止所做的:

#include "stdafx.h"
#include <iostream> 
#include <vector> 


int main(){
std::vector<char> one1; //A char vector that holds the first 'word'
std::cout << "Type in the first set of charactors: " << std::endl;
char o;
std::cin >> o;
int i = 0;
while (std::cin >> o && o != '\n' && o != 0) {
    one1[i] = o;
    i++;
    std::cin >> o;
}
std::cout << "Done"; 

    return 0;
}

一直返回错误,不是编译错误,而是在运行时出现这个错误:

调试断言失败!

程序:C:\WINDOWS\SYSTEM32\MSVCP140D.dll 文件:c:\program files (x86)\microsoft visual studio 14.0\vc\包括\向量 线路:1234

表达式:向量下标超出范围

我不知道出了什么问题,或者是什么导致了这种情况发生,我该怎么办?

【问题讨论】:

  • 为什么不读取字符串,然后拆分为字符?

标签: c++ vector


【解决方案1】:

您正在循环结束时读取一个字符,然后在 while 条件下立即读取另一个字符。所以每隔一个字符就会被忽略,你可能会错过'\n'

此外,[] 访问向量中的现有元素,您不能使用它来添加它。为此,您需要使用push_back

【讨论】:

    【解决方案2】:

    您的代码中有未定义的行为。您访问了一个不存在的元素。

    std::vector<char> one1;
    

    你的向量是空的。因此,如果你想添加它,你需要使用push_back:

    one1.push_back(o);
    

    【讨论】:

      【解决方案3】:

      如果您想阅读一行,请使用getline 函数。

      Getline 在字符串中存储一行,然后将该字符串转换为向量 (Converting std::string to std::vector<char>)

      #include <iostream> 
      #include <vector>
      #include <string>
      
      int main()
      {
        std::cout << "Type in the first set of charactors: " << std::endl;
        std::string line;
        std::getline(std::cin, line);
        std::vector<char> one1(std::begin(line), std::end(line)); //A char vector that holds the first 'word'
        std::cout << "Done"; 
        return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-21
        • 2017-04-18
        • 1970-01-01
        • 2020-05-17
        • 2021-08-07
        • 2021-09-21
        • 1970-01-01
        相关资源
        最近更新 更多