如何运行 while 循环直到到达新行?

How can I run through a while loop until a new line is reached?

本文关键字:新行 循环 while 何运行 运行      更新时间:2023-10-16

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

#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\include\vector 行: 1234

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

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

您正在循环结束时读取一个字符,并在 while 条件下立即读取另一个字符。所以每一个字符都会被忽略,你可能只是错过了'n'

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

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

std::vector<char> one1;

您的矢量为空。因此,如果要添加到其中,则需要使用push_back

one1.push_back(o);

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

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

#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;
}