Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/maven/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何运行while循环直到到达新行?_C++_Vector - Fatal编程技术网

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

C++ 如何运行while循环直到到达新行?,c++,vector,C++,Vector,我需要将通过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 f

我需要将通过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;
}
#包括“stdafx.h”
#包括
#包括
int main(){
std::vector one1;//保存第一个“单词”的字符向量
std::cout o;
int i=0;
而(std::cin>>o&&o!='\n'&&o!=0){
one1[i]=o;
i++;
标准:cin>>o;
}

std::cout您正在读取循环末尾的一个字符,并且在while条件下立即读取另一个字符。因此,每忽略一个字符,您就可能错过
“\n”


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

您正在读取循环末尾的一个字符,然后立即在while条件下读取另一个字符。因此,每忽略一个字符,您可能就会错过
'\n'


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

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

std::vector<char> one1;

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

std::vector<char> one1;

如果你想读一行,使用函数

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

#包括
#包括
#包括
int main()
{

std::cout如果您想读取一行,请使用函数

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

#包括
#包括
#包括
int main()
{

为什么不读取字符串,然后拆分为字符?为什么不读取字符串,然后拆分为字符?
#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;
}