gpt4 book ai didi

c++ - 如何在 C++ 中编写一个获取行,从文本文档中获取一行并将其添加到声明的变量中

转载 作者:行者123 更新时间:2023-11-28 06:19:30 25 4
gpt4 key购买 nike

这是下面的代码 我很难在学校完成作业 我目前在获取行上遇到困难 我需要程序从文本文档中获取 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;
}

最佳答案

有几种方法可以解决这个问题。您可以阅读该文件,直到到达您需要的行:

for (int i = 0; i < randNum; i++)
getline(infile, str);

// now str is the randNum line from the file

您也可以读取整个文件,然后只使用 randNum 作为索引:

std::vector<std::string> lines;
while(getline(infile, str))
lines.push_back(str);

// now lines[randNum - 1] is the randNum line of the file

如果您要在重新播放类型的情况下继续循环文件,我会使用第二种方法,除非文件很大。

关于c++ - 如何在 C++ 中编写一个获取行,从文本文档中获取一行并将其添加到声明的变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29565100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com