【发布时间】:2015-04-10 15:21:08
【问题描述】:
这是下面的代码我很难在学校完成作业我目前在获取行上遇到困难我需要程序在文本文档中从 0-20 中抓取随机行但我似乎收到此错误,因为我无法弄清楚如何正确编写 getline
hangman2.cpp:32: 错误:没有匹配函数调用 `getline(std::fstream&, int&)'
#include <iostream>
#include <fstream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
string hangmantxt;
int randNum;
string word;
string str;
randNum = rand() % 20;
fstream infile;
cout<<"enter the filename";
cin>>hangmantxt;
//Ask the user for the input filename
//Open the file (if it exists)
infile.open(hangmantxt.c_str());
if(!infile)
{
cout<<"file does not exist"<<endl;
}
while(getline(infile,randNum))
{
//Pick a random number between 1 and 20 = randNum;
//Pick the word at located at line number = randNum in the file;
}
/*
char c1, c2, c3, c4, c5, c6, c7;
bool a1, a2, a3, a4, a5, a6, a7;
Assign the 7 characters in the word to each of the 7 character variables;
Set all the Boolean variables to false;
while ((number of missed chances < 5)||(all boolean variables are true) )
{
if( any of the 7 characters are vowels)
{
set the corresponding Boolean variable to true;
}
if( any of the 7 boolean variables are true)
display the corresponding character;
else
display ‘_’;
Ask the user for a single character input
if(any of the characters match the user’s input)
{
set the corresponding Boolean variable to true;
}
if( the character did not match any of the 7 characters)
{
increment the number_of_chances_missed;
}
}
if(number_of_chances missed >= 5)
display “You lost!”;
else
display “You won!”;
display the word;
//These next 2 lines of code are required to set the read position of the
input file back to the beginning of the file
//Assuming your ifstream object is called infile
infile.clear();
infile.seekg(0, ios::beg);
Ask the user if he/she wants to play again;
}while ( the user wants to keep playing);
*/
infile.close();
return 0;
}
【问题讨论】:
-
您将
randNum传递给getline,而不是字符串。 -
getline 用于字符串。
-
你应该将文件逐行读入一个向量,然后使用随机数索引该向量。
标签: c++