Lompat ke konten Lompat ke sidebar Lompat ke footer

C++ Read Char and Int on Same Line

#ane

Reputation: 135

  • View blog
  • Posts: half-dozen,581
  • Joined: 11-July 07

Read one char at a fourth dimension from text file?

Posted 22 January 2010 - 03:13 PM

My assignment in C++ class for this week is to write ii programs. I to encrypt a four-digit integer and i to decrypt that same integer. The kickoff plan gets the ints from the user and writes them to a text file after encrypting each number. I finished that part, and it works like I desire it to.

Now I need to write the decryption part, and read each line of the file that is written by the first program. I want the plan to decrypt each integer and then impress them to another file.

How do I read merely ane graphic symbol on a line so that I can put it into an array? Also, how do you brand sure you get all the characters for each line, but only i line at a time? I know in that location are other (probably better?) means of doing this, such every bit read the whole line and then break up the integer into parts in guild to piece of work with each role. Only I prefer using an array.

This is the function that I recollect needs changing.

//read nums from file into assortment void read(int nums[], int SIZE, ifstream& inData) { 	 int nextNum; 	 //read first line from the file //how do I read one char at a fourth dimension from file? 	inData >> nextNum; 	//testify fault if file not establish 	if(!inData) 	{ 		  cout<< "Can't open up input file.\n"; 		  getchar(); 	} 	 	//while there are more lines to read from file 	int i = 0; //counter 	while(inData){	  		  nums[i] = nextNum;		 		  //read another line...this will put each line into an chemical element in the assortment 		  //then the whole file is read into 1 array instead of each line in one assortment 		  //with each char in the line put into ane element of the array 		  inData >> nextNum; 		  i++;    	}    }            

This programme does work in that it will read the file and bandy the values that I told it to bandy. They're just non the right values.

Here is the entire 2nd programme (unfinished, of form)

#include<iostream> #include<fstream> //for file reading & writing  using namespace std;  //read nums from file into assortment void read(int nums[], int SIZE, ifstream& inData) { 	 int nextNum; 	 //read outset line from the file //how exercise I read i char at a time from file? 	inData >> nextNum; 	//show fault if file not institute 	if(!inData) 	{ 		  cout<< "Can't open up input file.\due north"; 		  getchar(); 	} 	 	//while there are more lines to read from file 	int i = 0; //counter 	while(inData){	  		  nums[i] = nextNum;		 		  //read another line...this will put each line into an element in the assortment 		  //so the whole file is read into one array instead of each line in one assortment 		  //with each char in the line put into one chemical element of the array 		  inData >> nextNum; 		  i++;    	}    }  //bandy the outset digit with the 2nd, bandy the thrid digit with  //the 4th  void swap(int nums[]){ 	 int temp = nums[0]; 	 //swap kickoff two numbers 	 nums[0] = nums[1]; 	 nums[1] = temp; 	 //swap 2nd 2 numbers 	 temp = nums[2]; 	 nums[two] = nums[3]; 	 nums[3] = temp; }  //print the decrypted integer to the screen and to a file  void print(int nums[], int SIZE, ofstream& outData){    	//impress to screen and write to file.  	for(int i = 0; i<SIZE; i++){ 		cout<<nums[i]; 		outData << nums[i];     	//start next number on a new line 	cout << endl; 	outData << endl;  	} }  int main() { 	const int SIZE = 7; 	int nums[SIZE]; 	 	//open file to read 	ifstream inData; 	inData.open("EncFile.txt");  	 	//open file to write 	ofstream outData; 	outData.open("DecFile.txt");   	 	 	read(nums, SIZE, inData); 	//supervene upon(nums, SIZE); 	bandy(nums); 	print(nums, SIZE, outData);  	 	inData.close(); 	outData.shut();    	 } //Write a split up program(a second program, gosh) that inputs an encrypted  //four-digit integer and decrypts it to class the original number.            


Is This A Skilful Question/Topic? 0

  • +

#two n8wxs User is offline

Reputation: 972

  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Read one char at a time from text file?

Posted 22 January 2010 - 03:21 PM

You could read one character at a time. See istream::read

Or yous could read in the unabridged line and care for the string equally an array. Run across cord::operator[]

Encounter getline in the Strings library

This post has been edited by n8wxs: 22 January 2010 - 03:23 PM

#3 jjl User is offline

Reputation: 1271

  • View blog
  • Posts: 4,998
  • Joined: 09-June 09

Re: Read one char at a time from text file?

Posted 22 January 2010 - 03:35 PM

you lot can only apply istream::get() to read a file char past char

http://world wide web.cplusplus...am/istream/get/
example

vector<char> readbyChar(ifstream &file) { 	vector<char>data(0); 	char c; 	while(file.get(c)) 	{ 		data.push_back(c); 	} 	render information; }            

This post has been edited past ImaSexy: 22 January 2010 - 03:35 PM

#4 NickDMax User is offline

Reputation: 2255

  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: Read i char at a time from text file?

Posted 22 January 2010 - 03:37 PM

well you can read a char at a time by simply opening the file... just there is a problem hither:

#include <iostream> #include <fstream> #include <cstdlib> #include <ctime>  using namespace std;  int primary() { 	ofstream outfile ("numbers.txt"); 	//write out some random numbers... 	srand(fourth dimension(0)); 	for(int i = 0; i < 10; i++) { 		int number = 1000 + (rand() % 1000); 		outfile << number << endl; 	} 	outfile.shut(); 	 	//now to read some: 	ifstream infile("numbers.txt"); 	char ch; 	int count = 0; 	while(infile >> ch) { 		cout << ch; 		if (count % 4 == 3) { cout << endl; } 		count++;		 	} 	infile.close(); 	return 0; }            

The problem here is that there is not real style of telling when we accomplish the end of a line. I used count % 4 == three since I knew the numbers would all be four chars...

If you lot don't know that the file has a specific format then you accept a couple of options. You tin can employ getLine() with a cord and then grab the chars from the string, or yous tin can open the file in binary style when y'all will run into the whitespace chars.

#5 OliveOyl3471 User is offline

Reputation: 135

  • View blog
  • Posts: 6,581
  • Joined: 11-July 07

Re: Read one char at a fourth dimension from text file?

Posted 22 January 2010 - 04:sixteen PM

Thank you guys. :) I will try these suggestions subsequently I get back to the desktop computer. This laptop has no compilers on information technology. :(

One more affair, when you lot are reading one char at a time, will information technology read 0's? If one of iv-digit ints is 0000, will information technology read them all? The style my program is right now, it only reads prints 1 nada, or if there's a number like 0987 it will just read impress 987. I'm non certain what information technology'southward reading, I only know for certain what information technology'southward printing.

#half-dozen jjl User is offline

Reputation: 1271

  • View blog
  • Posts: 4,998
  • Joined: 09-June 09

Re: Read one char at a time from text file?

Posted 22 January 2010 - 04:57 PM

I would create a construction array and store a new line in every alphabetize of that structure.

example (compiled simply non tested)

enum { 	FILE_BAD, 	SUCCESS };  struct line_info { 	char line[250];  	line_info(void) 	{ 		memset(line,'\0',sizeof(line)); 	} };  int filesize(ifstream &file) { 	int count = 0; 	string temp = ""; 	while(getline(file,temp)) 		count++; 	file.clear(); 	file.seekg(ios::beg); //reset file point dorsum to the offset 	 	return count; }  int read( ifstream& inData, line_info*lines, int &SIZE)  { 	if(!inData.is_open()) 		render FILE_BAD; //return if bad file  	SIZE = filesize(inData); 	//classify some space for all of the lines  	lines = new line_info[SIZE];   	char c;  	int s_index = 0; //index for struct 	int l_index = 0; //alphabetize for array in struct 	  	while(inData.become(c)&&s_index<SIZE) 	{ 	 		if(c == '\n') //if a new line appears in file 		{ 			s_index++; //incriment to an empty struct 			l_index = 0; //clear line buffer back to zero 			keep; 		}  		lines[s_index].line[l_index] = c; 		 	} 	return SUCCESS; }            

This mail has been edited by ImaSexy: 22 January 2010 - 04:59 PM

#7 OliveOyl3471 User is offline

Reputation: 135

  • View blog
  • Posts: 6,581
  • Joined: 11-July 07

Re: Read ane char at a time from text file?

Posted 22 January 2010 - 05:47 PM

What I need to practice as well simply reading a char at a time is to read or salve it equally an int.

This works if I was going to save it as a char, but I demand to perform arithmetic operations on each number after it'southward in the array. It doesn't put the correct numbers into the array. See?

              ifstream is;  char c;  int i =0; 	is.open up("EncFile.txt");   while (is.proficient())	 // loop while extraction from file is possible   { 	c = is.become();	   // get character from file 	if (is.good()) 	  cout <<"c"<< c<<endl; 	  nums[i]=is.get(); 	  cout<<endl<<nums[i]<<" is nums i"<<endl; 	  i++;   } }            

If there's a way to change c's value from char to int and then place it in the array I guess that would work. Though it seems like a roundabout way of doing things.

#8 n8wxs User is offline

Reputation: 972

  • View blog
  • Posts: three,878
  • Joined: 07-January 08

Re: Read one char at a time from text file?

Posted 22 January 2010 - 06:03 PM

Have a look at

// matrices.cpp : Defines the entry point for the panel application. // #include "stdafx.h"  #include <iostream> #include <fstream>  using namespace std;  void read (int [], int, ifstream&); void swap (int []); void print(int [], int, ofstream&);  int _tmain(int argc, _TCHAR* argv[]) { 	const int SIZE = vii; 	int nums[SIZE];  	//open file to write 	ofstream outData; 	outData.open up("oliveoyl.txt", ios::out | ios::trunc);    	for (int i = 0; i < SIZE; i++) { 		outData.write((char *) &i, 1); 	}  	outData.close();    	//open file to read 	ifstream inData; 	inData.open("oliveoyl.txt");  	//open up file to write 	//	ofstream outData; 	outData.open("DecFile.txt");     	read(nums, SIZE, inData); 	//replace(nums, SIZE); 	swap(nums); 	impress(nums, SIZE, outData);  	inData.close(); 	outData.close();    	system("interruption"); 	return 0; } void read(int nums[], int SIZE, ifstream& inData) { 	char c;  	for (int i = 0; i < SIZE; i++) { 		inData.read(&c, 1);  		if (inData.good()) 			nums[i] = c;  		else { 			cout << "Couldn't read byte #" << i << endl; 			inData.articulate(); 		} 	} 	// int nextNum; 	// //read outset line from the file //how do I read one char at a time from file? 	//inData >> nextNum; 	////show error if file not institute 	//if(!inData) 	//{ 	//	  cout<< "Tin can't open input file.\n"; 	//	  getchar(); 	//}  	////while there are more lines to read from file 	//int i = 0; //counter 	//while(inData){	 	//	  nums[i] = nextNum;		 	//	  //read some other line...this will put each line into an chemical element in the array 	//	  //and so the whole file is read into 1 array instead of each line in ane array 	//	  //with each char in the line put into one element of the assortment 	//	  inData >> nextNum; 	//	  i++;   	//}   }  //swap the outset digit with the second, swap the thrid digit with //the 4th void swap(int nums[]){ 	int temp = nums[0]; 	//bandy starting time two numbers 	nums[0] = nums[ane]; 	nums[1] = temp; 	//swap 2nd two numbers 	temp = nums[2]; 	nums[2] = nums[3]; 	nums[3] = temp; }  //print the decrypted integer to the screen and to a file void print(int nums[], int SIZE, ofstream& outData){   	//print to screen and write to file. 	for(int i = 0; i<SIZE; i++){ 		cout<<nums[i]; 		outData << nums[i];  		//starting time next number on a new line 		cout << endl; 		outData << endl; 	} }            

Here's the output:

Quote

1
0
3
2
four
5
half-dozen
Press any central to continue . . .


#nine jjl User is offline

Reputation: 1271

  • View blog
  • Posts: 4,998
  • Joined: 09-June 09

Re: Read one char at a fourth dimension from text file?

Posted 22 January 2010 - 06:47 PM

Cant u just use atoi to covert each char to an int

#x NickDMax User is offline

Reputation: 2255

  • View blog
  • Posts: ix,245
  • Joined: 18-Feb 07

Re: Read one char at a time from text file?

Posted 22 Jan 2010 - 07:18 PM

Why utilise atoi for 1 char...

digit = ch - '0';

call up that chars ARE numbers.

#11 jjl User is offline

Reputation: 1271

  • View blog
  • Posts: 4,998
  • Joined: 09-June 09

Re: Read one char at a time from text file?

Posted 22 January 2010 - 08:26 PM

oh your completly right Nick, i seem to always forget your can still perform aritmetic operation on chars.

#12 OliveOyl3471 User is offline

Reputation: 135

  • View blog
  • Posts: 6,581
  • Joined: 11-July 07

Re: Read one char at a time from text file?

Posted 22 January 2010 - 09:40 PM

Well I finally got information technology working. Give thanks you all for your kind aid and nudges in the right direction. :)

This is actually a little different than what I had originally intended, but hey...as long as it works, eh?

Cheers to baavgai, besides. Yous're the coolest! B)

#include<iostream> #include<fstream> //for file reading & writing #include<conio.h> //for getch()  using namespace std;  //print the decrypted integer to the screen and to a file  void print(string nums[], ofstream& outData){    	//print to screen and write to file.  	for(int i = 0; i<4; i++){ 		cout<<nums[i]; 		outData << nums[i]; 	}  }  //swap the first digit with the 2d, swap the 3rd digit with  //the 4th  void swap(string nums[], ofstream& outData){ 	 cord temp = nums[0]; 	 //swap showtime two numbers 	 nums[0] = nums[1]; 	 nums[one] = temp;  	 //bandy second two numbers 	 temp = nums[2]; 	 nums[2] = nums[3]; 	 nums[3] = temp; 	 impress(nums, outData); }  //replace numbers  void replace(ifstream& inData, ofstream& outData){  	char ch; 	//open file to read     inData.open("EncFile.txt");    string nums[4]; //array to hold each graphic symbol    while (inData.good()){ // loop while extraction from file is possible 		 for(int i =0; i< 5; i++){  //5 because iv integers plus new line grapheme will be read 			 			 ch = inData.get();   // become character from file 			 if (inData.skilful()){ 			 //for each char in cord, alter it back to original (before swapping) 				  switch(ch){ 					   case '0': ch = '5'; 					   suspension; 					   example '1': ch = 'vi'; 					   interruption;		   					   case 'two': ch = '7'; 					   pause;		   					   instance '3': ch = 'eight'; 					   break;		   					   example '4': ch = '9'; 					   intermission;		   					   case '5': ch = '0'; 					   break;		   					   case '6': ch = 'i'; 					   break;		   					   case '7': ch = 'two'; 					   suspension;		   					   example '8': ch = '3'; 					   interruption;		   					   example 'ix': ch = '4'; 					   interruption;  					   case '\n': ch = '\n';					   				  }//end switch 				  if(ch == '\n'){ //don't add new line character to array			  				  }//stop if 				  else{ 					  nums[i] = ch;//but if ch is non new line 					   				  }//cease else 			 }//cease if 		 }//end for 		 swap(nums, outData);  			   outData<<endl; 			   cout<<endl;	      }//end while }//terminate replace()  int chief() {  	ifstream inData; 	ofstream outData; 	//open file to write 	outData.open("DecFile.txt");   	 	replace(inData, outData);  	inData.shut(); 	outData.close();    	getch();  } //Write a separate plan(a 2d program, gosh) that inputs an encrypted  //four-digit integer and decrypts it to form the original number.            

#13 OliveOyl3471 User is offline

Reputation: 135

  • View blog
  • Posts: 6,581
  • Joined: 11-July 07

Re: Read one char at a time from text file?

Posted 22 January 2010 - ten:47 PM

Now I come across why programmers cuss and then much! :blink:

Is there a mode to set this so that it will still be able to read one char at a time, and as well practise a priming read (or whatever information technology takes to go far work properly) and then it won't get past the end of the file and input one extra line into my text file?

              while (inData.good()){ // loop while extraction from file is possible 		 for(int i =0; i< 5; i++){ //v because iv integers plus new line grapheme will be read    			 ch = inData.become(); // become graphic symbol from file            

I tried

inData>>ch; while(inData>>ch)            

But it messed up the whole thing. :(

#14 NickDMax User is offline

Reputation: 2255

  • View blog
  • Posts: ix,245
  • Joined: xviii-February 07

Re: Read i char at a fourth dimension from text file?

Posted 22 Jan 2010 - 10:57 PM

you know... rather than that long switch yous could use a little math formula:

#include<iostream>  using namespace std;  char encode(char ch) { 	if (ch >= '0' && ch <= '9') { 		ch = (ch - '0' + 5 ) % 10 + '0'; 	} 	render ch; }  int main() { 	for (char ch = '0'; ch <= 'ix'; ch++) { 		cout << ch << " --> " << encode(ch) << endl; 	}    	render 0; }            

#fifteen OliveOyl3471 User is offline

Reputation: 135

  • View blog
  • Posts: 6,581
  • Joined: eleven-July 07

Re: Read 1 char at a time from text file?

Posted 23 January 2010 - 09:05 AM

View PostNickDMax, on 22 Jan, 2010 - xi:57 PM, said:

you know... rather than that long switch y'all could apply a petty math formula

That's pretty cool how y'all tin practise math on a character like that. And information technology shortens the code. :)

I did get mine working, finally. Possibly, now that information technology works, I'll try making information technology work meliorate. Of course I'm going to hand the thing in, every bit is, considering I'yard kind of sick of it at the moment and I really desire to make sure I get credit for information technology...in case the calculator messes upward or something. But doing math on chars is pretty neat. B)

Hither's how I changed it to brand it work like I want:

//replace numbers  void replace(ifstream& inData, ofstream& outData){     //open file to read     inData.open("EncFile.txt");    char ch;    string nums[four]; //array to hold each character    if(!inData){ //make sure file opens 		 cout<< "Can't open up input file.\north"; 		 getchar();    }    ch = inData.get(); // go character from file, priming read    while (inData.practiced()){ // loop while extraction from file is possible 		 for(int i =0; i< 5; i++){ //5 because 4 integers plus new line character volition exist read    			 if (inData.good()){  				  //for each char in string, alter it dorsum to original (before swapping) 				  switch(ch){ 					   //long former switch hither 				    				  }//terminate switch 				  if(ch == '\north'){ //don't add new line grapheme to array			  				  }//end if 				  else{ 					  nums[i] = ch;//simply if ch is not new line 					   				  }//cease else 			 }//stop if 			 ch = inData.get(); // get another grapheme from file 		 }//finish for 		 swap(nums, outData); 		 outData<<endl; 		 cout<<endl;	     }//stop while }//end replace()            

wilsonmandetlable1940.blogspot.com

Source: https://www.dreamincode.net/forums/topic/151417-read-one-char-at-a-time-from-text-file/

Posting Komentar untuk "C++ Read Char and Int on Same Line"