如何运行 while 循环直到到达新行?
How can I run through a while loop until a new line is reached?
我需要设置一个通过 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;
}
相关文章:
- 使用新行和不使用新行读取文件
- 遇到新行时,有没有办法停止istream_iterator
- PangoLayout 中忽略的新行
- 使用 clang 格式时,当行很大时,如何将右括号分成新行?
- 如何检测将文本文件读入 int 数组的新行
- 当 getline 直到新行才读取时会发生什么?
- 添加新行时工作代码引发异常.调试技巧?
- QTree查看新行,没有布局就不可见已更改
- 新行上的 clang 格式右括号
- C++流:保存到新行而不是覆盖旧行
- (C++) 使用诅咒打印从文件中读入的新行
- 按升序输出整数时,将最后一个整数放在新行上
- 用C++计算输入文本的新行数
- 为什么我的代码在终端中没有输出任何内容.开始新行没有错误
- WriteConsoleOutputCharacterW - 我的新行在哪里?
- 如何制作 arduino 串行循环(连续接收数字)
- 如何运行 while 循环直到到达新行?
- C++:进入循环后增加新行
- 仅在向量末尾打印新行 - "if"语句在"for"循环之外
- 如何跳到文件中的新行并重复循环