-1

supposing i made a .txt file and put string like

123+abc
456+def

then how can i read 456 after 123 in case 123 is not that number i want

i tried getline() but i dont know how to read 123 and pass to next line when i tried, it doesnt work

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

int main(){
int check=0;
ifstream myfile;
myfile.open("texttext.txt");
string tmp_string;
int tmp_int;

while(!myfile.eof){
  tmp_string=getline(myfile);
  getchar(tmp_int,tmp_string);
  if(tmp_int==the_number) {
    check=1;
    cout<<"found it"<<endl;
    break;
  }
}
myfile.close():
if(check==0) cout<<"non match"<<endl;
return 0;
}
463035818_is_not_a_number
  • 64,173
  • 8
  • 58
  • 126
jan
  • 1
  • 1
  • 123+abc\n 456+def – jan Sep 30 '19 at 10:14
  • 1
    read this: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons – 463035818_is_not_a_number Sep 30 '19 at 10:16
  • please post real code, yours has `the_number` not declared, and you are missing `std::` for all types. Please read about [mcve]. And please try to explain better what is the meaning of "it doesnt work", when I compile this code I get a wall of compiler errors out of which probably one or two are related to your actual problem – 463035818_is_not_a_number Sep 30 '19 at 10:19

1 Answers1

0

Assuming that the format of the file is \d{3}.* for each line, then the following code will do.

int main() {
    bool check = false;
    std::ifstream myfile;
    myfile.open("texttext.txt");
    std::string tmp_string;
    int tmp_int;
    int the_number = 456;

    while (getline(myfile, tmp_string)) {
        tmp_int = stoi(tmp_string.substr(0, 3));
        if (tmp_int == the_number) {
            check = true;
            std::cout << "found it" << std::endl;
            break;
        }
    }
    myfile.close();
    if (!check) std::cout << "non match" << std::endl;
    return 0;
}
CodePleasure
  • 1
  • 1
  • 1