C++,<char>逐个字符地从文件中将字符读取到向量中
C++, reading chars into a vector<char> from a file, character by character
我正试图将名为"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);
}
或者更改函数的返回类型。
-
从文件中读取第一行或(需要多少行)到字符串
-
从开始创建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;
}
相关文章:
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 如何从文本文件中读取数值,直到遇到字符类型?
- 使用 fopen 打开 .pak 文件并使该文件应用于 const 无符号字符* (C++)
- 如何像在 C++ 中处理数组一样对 .txt 文件中的字符进行寻址?
- 尝试将字符串从文件读取到无符号字符向量中
- 如何在C++中反转文本文件中字符的顺序?
- 生成随机.txt文件,10行,10列。充满随机:"*"、"#"、"@"。然后将随机字符替换为'P'
- 如何存储 unicode 字符并将其输出到文件?
- 无法将整个文本文件复制到字符数组
- 仅读取文件末尾的最后 3 个字符,并将其另存为 int
- 将未签名的字符写入输出文件
- 从我的 2DgridArray 中的文本文件中获取每个字符
- ifstream 读取的字符与文件中写入的字符不同
- VSCode C++调试文件名中包含中文字符的文件时插件损坏
- 从文本文件 (C++) 生成字符矩阵
- 使用指针编译代码后,.cpp文件将变为随机字符
- 在c++中读取文件时,它如何自动将字符放入字符数组,将数字放入整数变量
- 跨平台UTF-8字符文件数据编码/解码