C++ Problem accessing record from a Text file

Hi I new here. I am a beginner at programming.
I am having problems updating records in a text file using C++, so I made a test case on the side discovering something weird.
When I access a record and try to print only the first three entries. There are no problems.

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

using namespace std;

int main()
{
	fstream file("t.txt");
	
	int a; string b; int c;
	int p = 1;
	while(file>>a>>b>>c){
		if(a == 1){
			cout <<a<<b<<" "<<c;
		}
	}
	
	return 0;
}

But when I try to print the fourth entry (It was supposed to be in date format but I removed hyphens to see if it solves the problem. It was also originally a string) it does not print anything at all.

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

using namespace std;

int main()
{
	fstream file("t.txt");
	
	int a; string b; int c; int d;
	int p = 1;
	while(file>>a>>b>>c>>d){
		if(a == 1){
			cout <<a<<b<<" "<<c<<d;
		}
	}
	
	return 0;
}

Here is the text file;

0 husnain 20
1 husnain 21 22222222
2 husnain 22
3 husnain 23
4 husnain 24

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

This is expecting every 4 values to be a int, string, int and int, but this is not how your input is structured.

Thank you! You are a life saver. There are so many things you only learn like this. I do not think I would have learned this anywhere else. I am so sorry about the backticks. I am here for the first time. I will keep this in mind next time.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.