C++,<char>逐个字符地从文件中将字符读取到向量中

C++, reading chars into a vector<char> from a file, character by character

本文关键字:字符 文件 向量 读取 lt char gt C++      更新时间:2023-10-16

我正试图将名为"board.txt"的文件的前7个字符读入一个向量<'char>但是由于某些原因我遇到了问题。我对C++不太熟悉,所以任何建议都将不胜感激,这是我迄今为止拥有的代码

    //rack
int charCount = 0;
char ch;
ifstream rackIn("board.txt");
while(rackIn.get(ch) && charCount < 7){
    this->getMyRack().push_back(ch);
}

下面是上面代码中使用的getMyRack函数:

vector<char> board::getMyRack(){
    return this->myRack;
}

myRack是一个字符矢量

我试着在我的主要使用这个测试:

for (int i = 0; i < test->getMyRack().size(); ++i){
    cout << test->getMyRack().at(i);
} 

但它没有输出任何内容,为什么我正在读取的字符没有添加到我的字符向量中?

因为您没有在向量中放入char。函数getMyRack()返回向量,但不返回向量的地址。您可以将方法添加到您的类板中以添加字符,例如:

 void board::addChar(char c){
     this->myRack.push_back(c);
   }

然后调用这个函数:

 while(rackIn.get(ch) && charCount < 7){
    this->addChar(ch);   
  }

或者更改函数的返回类型。

  1. 从文件中读取第一行或(需要多少行)到字符串

  2. 从开始创建7个字符的子字符串

       std::ifstream file("board.txt");
       std::string str;
        // to read single line
        std::getline(file, str);
      // to read 7 chars 
      str= str.substr(0,7); 
      vector<char> char_buf;
      for(size_t i =0; i <= str.size();i++)
      {
         char_buf.push_back(str[i]) 
     }
     // use the char_buf 
    

更简单或第二种方法是使用

            #include<fstream> // for ifstream
              
            #include <cstdlib> // for exit()
            std::string file_name ="board.txt";
            
            std::ifstream input_stream;
           
            std::vector<char> char_buf;
            
             input_stream.open(file_name); 
            if(input_stream.fail()) { exit(0);}
             int char_no=0;
            
           while(i<=7)
                      
            {
             char c = input_stream.get();
              char_buf.push_back(c);
               i++;              
             }
             
           // use char_buf
          
std::string str;
   int char_count=0;
    // Read the next line from File untill it reaches the 7.
    while (std::getline(in, str)&& char_count!=7)
    {
        // Line contains string of length > 0 then save it in vector
        if (str.size() > 0)
            your_char_vector.push_back(str);
              char_count++;
           if(char_count==7)
              break;
    }