gpt4 book ai didi

C++ 代码获取文件行并读取该行的第二个字?

转载 作者:太空宇宙 更新时间:2023-11-03 10:37:15 25 4
gpt4 key购买 nike

#include <iostream>
#include <string>
#include <fstream>

using namespace std ;


string strWord( int index , string line)
{
int count = 0;
string word;
for ( int i = 0 ; i < line.length(); i++)
{
if ( line[i] == ' ' )
{
if ( line [i+1] != ' ')
{

count ++;
if ( count == index)
{
return word;
}
word ="";
}
}
else
{
word += line[i];
}
}
}







int main ( )
{
ifstream inFile ;
inFile.open("new.txt");
string line , id;

cout <<"Enter id : ";
cin >>id;
while(!inFile.eof() )
{
getline ( inFile , line );
if ( strWord ( 1, line ) == id )
{
cout <<strWord ( 2 , line ) <<endl;
break;
}
}
system("pause");
}

问题是:有人可以向我解释一下吗?我不明白它在做什么,我的意思是我明白了这个概念,但每一行在做什么?

最佳答案

你想要每一行的评论

// function that returns a word from 'line' with position 'index'
// note that this is not a zero based index, first word is 1,
// second is 2 etc ..
string strWord(int index, string line)
{
int count = 0; // number of read words
string word; // the resulting word
for (int i = 0 ; i < line.length(); i++) { // iterate over all characters in 'line'
if (line[i] == ' ') { // if this character is a space we might be done reading a word from 'line'
if (line[i+1] != ' ') { // next character is not a space, so we are done reading a word
count++; // increase number of read words
if (count == index) { // was this the word we were looking for?
return word; // yes it was, so return it
}
word =""; // nope it wasn't .. so reset word and start over with the next one in 'line'
}
}
else { // not a space .. so append the character to 'word'
word += line[i];
}
}
}


int main( ) // main function of the program, execution starts here
{
ifstream inFile; // construct input file stream object
inFile.open("new.txt"); // associate the stream with file named "new.txt"
string line, id; //

cout << "Enter id : "; // write "Enter id :" to console
cin >> id; // read input from console and put the result in 'id'

while (!inFile.eof()) { // do the following as long as there is something to read from the file
getline(inFile, line); // read a line from the file and put the value into 'line'
if (strWord(1, line) == id) { // if the first word in 'line' equals 'id' ..
cout << strWord(2, line) << endl; // prints the second word in 'line'
break; // exits the while loop
}
}

system("pause"); // pause the program (should be avoided)
}

关于C++ 代码获取文件行并读取该行的第二个字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/928777/

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