我试图将一个名为 "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是一个char向量
我试着在我的主程序中用这个来测试,但没有任何输出。
for (int i = 0; i < test->getMyRack().size(); ++i){
cout << test->getMyRack().at(i);
}
但它没有任何输出,为什么我读入的字符没有被添加到我的向量中?
因为你没有在你的向量中加入字符。你的函数 getMyRack()
返回向量,但不返回向量的地址。例如,你可以在你的类板上添加方法来添加char。
void board::addChar(char c){
this->myRack.push_back(c);
}
然后调用这个函数
while(rackIn.get(ch) && charCount < 7){
this->addChar(ch);
}
或者改变函数的返回类型
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;
}