How can I extract and print every 5 digits from a txt file using C++ file i/o?

  • Context: C/C++ 
  • Thread starter Thread starter ACLerok
  • Start date Start date
  • Tags Tags
    C++ File
Click For Summary
SUMMARY

The discussion focuses on extracting and printing every 5 digits from a text file using C++ file I/O. The provided code utilizes the fstream library to open a file named "digitsofe.txt" and attempts to read 5-digit segments. However, the second segment fails to print due to improper handling of the file pointer and error flags. The solution involves checking the error state of the file stream and correctly managing the file pointer with seekg.

PREREQUISITES
  • Understanding of C++ file I/O using fstream
  • Knowledge of string manipulation in C++
  • Familiarity with error handling in file operations
  • Basic understanding of the getline function in C++
NEXT STEPS
  • Learn how to use C++ fstream error flags for debugging
  • Research the correct usage of seekg for file pointer manipulation
  • Explore string handling techniques in C++ for better data extraction
  • Investigate alternative methods for reading fixed-length records in C++
USEFUL FOR

C++ developers, students learning file I/O operations, and anyone interested in string manipulation and error handling in C++ programming.

ACLerok
Messages
194
Reaction score
0
i have a txt file full of numbers and i just want to take the first 5 digits, save it has one number, shift over 1 digit, take another 5 digits, save it, and so on until the end of the file

here is the code
Code:
	fstream Prime;
	Prime.open("digitsofe.txt");
	
	if (!Prime.is_open()) { cout << "unable to open"; }
	else if (Prime.is_open()) {
		cout << "File opened successfully\n";
		Prime.getline(str2,6);
		cout << str2 << endl;
		Prime.seekg(1);
		Prime.getline(str2,6);
		cout << str2;
		
		Prime.close();
}
right now I'm just trying to print the first 5 digits and then the next 5 digits but the second number won't print. what am i doing wrong?

I tried using the get function but using atoi kept giving errors.
 
Technology news on Phys.org
You are going right, so now, check the error flags in Prime.

count << str2 << endl;
 

Similar threads

  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 16 ·
Replies
16
Views
4K
  • · Replies 6 ·
Replies
6
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 9 ·
Replies
9
Views
4K
  • · Replies 10 ·
Replies
10
Views
2K
  • · Replies 13 ·
Replies
13
Views
2K
  • · Replies 8 ·
Replies
8
Views
6K
  • · Replies 7 ·
Replies
7
Views
2K