Convert a character to an integer in C++ language - c++

I want to convert from char to integer,
following is the code-
FILE *p;
char temp;
int temp_int;
p=fopen("week3data","r");
temp=getc(p);
temp_int=atoi(temp)
number in file goes from 1 to 200, need some guidance.

If you're using C++, please use C++ SL:
std::fstream stream("file.txt", std::ios_base::in);
float number;
stream >> number;
std::cout << number;
Edit: Don't forget to check if your stream is valid:
if (!stream) {
throw std::runtime_error("Cannot open file");
}

If you're reading from a file, you shouldnt be using
temp=getc(p);
and if you use
temp=fgetc(p);
and the number is, for example 200, you will only read the "2".
so the answer is:
better use
char * buffer;
fgets(buffer,10, p);
temp_int=atoi(buffer);

Related

Recursive Descent Parser Help (Not reading a text file string)

char input[100]; //Used to check grammar
char *s;
int main(int argc, char *argv[]) {
ifstream fin("input.txt"); //Open input file
while (fin>>input) { //Store text in input[]
s = input; //Point c at the input text
cout<<"String read from file: "<<input<<endl; //Show input text
if (A() && *s == '\0') { //Testing the grammar
cout<<"The string \""<<input<<"\" is in the language."<<endl;
}
else cout<<"The string \""<<input<<"\" is not in the language."<<endl;
cout<<endl; //Formatting for output in console
}
fin.close(); //Close input file
return 0;
}
Can someone tell me what i am doing wrong here. The parser is not reading string from the text file.
Let's treat this like two problems.
Problem 1: Reading in the file.
I've stripped out everything that isn't absolutely essential to reading the data in.
char input[100]; //Used to check grammar
int main(int argc, char *argv[]) {
ifstream fin("input.txt"); //Open input file
while (fin>>input) { //Store text in input[]
cout<<"String read from file: "<<input<<endl; //Show input text
}
return 0;
}
Nothing really wrong here, but you should seriously consider replacing char input[100]; with std::string input; to save you headaches with large tokens. For example, watch what happens here:
int main()
{
stringstream stream("1234567890"); // pack ten characters into stream
// note: no whitespace.
char snookums[] = "snookums";
char array[5];
cout << snookums << endl; // prove contents of snookums
stream >> array; // read up to first whitespace from stream into array
cout << array << endl; // display what we read.
cout << snookums << endl; // oh dear. Now look at poor snookums!
return 0;
}
output:
snookums
1234567890
67890
Despite array being size 5, it contains all 10. Or does it? Nope. Sadly poor snookums got run over. This won't happen with strings.
For all we know fin>>inputjust read 30000 characters from a whitespace-free file, annihilated the rest of your program's memory, and the program died before printing out anything.
Anyway, your code leaves a few questions:
Are you actually able to open the file? You don't know, really. You never checked.
Was the file empty? Also don't know. You didn't tell us. This is one of the things folks are getting on about in the comments.
None of this fixes anything, but hopefully gives you a better idea what's going wrong.
string input; // using string in case the data you're reading is incompatible
//with a 100 character char array.
int main(int argc, char *argv[]) {
ifstream fin("input.txt"); //Open input file
if (fin.is_open()
{
while (fin>>input)
{ //Store text in input
cout<<"String read from file: "<<input<<endl; //Show input text
}
}
else
{
cout << "Failed to open file." << endl;
}
return 0;
}
Once you know if you are actually reading in data, and if not, why not.
Problem 2: language parsing.
We can't help you here. No information was provided, but a few notes on coding style because they will help you ask future questions:
A() is meaningless to everyone but you. Give it a descriptive name so that someone other than you has some hints about what it does. A() takes no parameters. I assume that's because it is operating on input. OK, but why not pass input in? The cost is minimal and it provides more information to readers. Note how commenters zeroed in on A() right away? That's fear. The good kind of fear. We have no [insert expletive here] clue what it is or what it does, so it is instantly scrutinized.
A(input) reads to me as "A does something to input." I don't know what it does, but it does it to input. Unless the writer of the program has a history of doing silly stuff, it probably only does stuff to input and I don't have to fear this function nearly as much.
LanguageInterpreter() tells me that a language interpreter was run. Not much, but if I'm looking tor a bug in the file reading code, I'm not likely to find it in there. Unfortunately it also tells me that LanguageInterpreter is feasting on global data and Crom only knows what sort of side effects it could have on the rest of the program.
LanguageInterpretter(input) tells me a lot. For one thing it tells me that I can get on with my day because it has nothing to do with, or better have nothing to do with, the reading in of the data file. I'll check other places for bugs first.
string *s;
int main()
{
string input;
ifstream fin("input.txt");
if(fin.is_open())
{
while(getline(fin,input))
{
s=&input;
if (A() && *s == '\0') /* error: no match for 'operator==' in '* s == '\000''*/
{ //Testing the grammar
cout<<"The string \""<<*s<<"\" is in the language."<<endl;
}
else cout<<"The string \""<<*s<<"\" is not in the language."<<endl;
cout<<endl;
}
}
fin.close();
return 0;
}

reading a file with a running name from 0 to N

I have N+1 files in a folder called b0.txt,b1.txt,b2.txt, ....,bN.txt.
I would like to open them inside a loop because for each of them I would like to copy the first 15 characters inside an array.
The code lines I wrote are basically:
int main(){
int N=4;
int i;
char number [15];
for(i=0; i< N; i++){
ifstream OpenFile("b%i.txt");
int l=0;
while(!OpenFile.eof()) {
OpenFile >> number [l];
l++;
}
OpenFile.close();
}
}
I'm using Dev C++ and when I compile these code lines no errors are shown. However, I'm not able to run the program.
Do you have any tip?
You should build the string name of the file. You might try:
char bufname[64];
snprintf(bufname, sizeof(bufname), b%i.txt", i);
ifstream OpenFile(bufname);
or use std::string or std::ostringstream tricks.
The filename "b%i.txt" is used explicitly as written, not as a printf-style format specifier.
You can either use sprintf, e.g.:
char filename[512];
sprintf(filename, "b%i.txt", i);
ifstream OpenFile(filename);
or use the C++ ostringstream, e.g.:
std::ostringstream filename;
filename << "b" << i << ".txt";
ifstream OpenFile(filename.str().c_str());
"b%i.txt" doesn't put i into the string... you can use:
std::ostringstream oss;
oss << 'b' << i << ".txt";
if (std::ifstream f(oss.str().c_str()))
...f is an open stream - use it here...
else
std::cerr << "couldn't open file " << oss.str() << '\n';
Don't test for eof - it doesn't work like that. Just use read and gcount:
if (OpenFile.read(number, sizeof number) && f.gcount() == sizeof number)
...you got the data...
else
std::cerr << "unable to read 15 characters from " << oss.str() << '\n';
(FWIW, eof is set after an input operation is concluded or aborted due to hitting eof, so it's not false before you attempt input, and it not being set doesn't guarantee the next operation will succeed - how could it if the stream doesn't yet know what you'll try to read?)
Your program does nothing to get the value of i into the string that you are sending to OpenFile(). You have to create a string with a textual representation of i embedded in it, which this code does not do.
Change
OpenFile("b%i.txt")
to
char filename[8];
sprintf(filename, "b%d.txt", i); // Create filename with embedded number
ifstream OpenFile(filename);
ifstream OpenFile("b%i.txt");
You're not writing in Batch! Here you can't put number variable using %name syntax.
If you're using C++11, I'd recommend to use std::to_string and type:
ifstream OpenFile("b"+std::to_string(i)+".txt");
for the code line where you are reading the characters in array
"OpenFile >> number [l];"
the compiler will through the error "segmentation fault" due to array out of bound.
so you have to add condition like this
if( l <= 14) // bcz you are starting with l=0
{
OpenFile >> number [l];
}
else
break;

Read a binary file (jpg) to a string using c++

I need to read a jpg file to a string. I want to upload this file to our server, I just find out that the API requires a string as the data of this pic. I followed the suggestions in a former question I've asked Upload pics to a server using c++ .
int main() {
ifstream fin("cloud.jpg");
ofstream fout("test.jpg");//for testing purpose, to see if the string is a right copy
ostringstream ostrm;
unsigned char tmp;
int count = 0;
while ( fin >> tmp ) {
++count;//for testing purpose
ostrm << tmp;
}
string data( ostrm.str() );
cout << count << endl;//ouput 60! Definitely not the right size
fout << string;//only 60 bytes
return 0;
}
Why it stops at 60? It's a strange character at 60, and what should I do to read the jpg to a string?
UPDATE
Almost there, but after using the suggested method, when I rewrite the string to the output file, it distorted. Find out that I should also specify that the ofstream is in binary mode by ofstream::binary. Done!
By the way what's the difference between ifstream::binary & ios::binary, is there any abbreviation for ofstream::binary?
Open the file in binary mode, otherwise it will have funny behavior, and it will handle certain non-text characters in inappropriate ways, at least on Windows.
ifstream fin("cloud.jpg", ios::binary);
Also, instead of a while loop, you can just read the whole file in one shot:
ostrm << fin.rdbuf();
You shouldn't read the file to a string because it is legal for a jpg to contain values that are 0. However in a string, the value 0 has a special meaning (it's the end of string indicator aka \0). You should instead read the file into a vector. You can do this easily like so:
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
int main(int argc, char* argv[])
{
std::ifstream ifs("C:\\Users\\Borgleader\\Documents\\Rapptz.h");
if(!ifs)
{
return -1;
}
std::vector<char> data = std::vector<char>(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());
//If you really need it in a string you can initialize it the same way as the vector
std::string data2 = std::string(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());
std::for_each(data.begin(), data.end(), [](char c) { std::cout << c; });
std::cin.get();
return 0;
}
Try opening the file in binary mode:
ifstream fin("cloud.jpg", std::ios::binary);
At a guess, you were probably trying to read the file on Windows and the 61st character was probably 0x26 -- a control-Z, which (on Windows) will be treated as marking the end of the file.
As far as how to best do the reading, you end up with a choice between simplicity and speed, as demonstrated in a previous answer.

How do I read character by character from a text file and put it in a character array?

I'm trying to read character by character from a text file until EOF, put them into a character array, so that I can manipulate it after. Compiled with g++ without errors, and when run, I'm prompted for the input file but then it just hangs.
int main (int argc, char *argv[]) {
string filename;
ifstream infile;
char *cp, c[1024];
memset (c, 0, sizeof(c));
cp = c;
cout << "Enter file name: " << endl;
cin >> filename;
//open file
infile.open( filename.c_str() );
//if file can't open
if(!infile) {
cerr << "Error: file could not be opened" << endl;
exit(1);
}
while (!infile.eof()); {
infile.get(c, sizeof(infile));
// get character from file and store in array c[]
}
}//end main
You should try the istream::read() method rather than get(). This will help resolve any buffer overruns:
unsigned int chars_read = 0;
//...
// Read in the file.
if (!infile.read(c, sizeof(c))
{
// Handle the read error here.
// Also check for EOF here too.
}
// Obtain the number of characters actually read.
chars_read = infile.gcount();
First off, you don't want to test for eof()! Somehow I start to feel like Don Quixote having found my windmills. However, I do know that you need to check that the input was successful after trying to read it because before attempting to read the stream can't know whether it will be successful.
You program actually doesn't hang! It just waits for you to enter sizeof(infile) characters or end the input (e.g., using Ctrl-D on UNIXes and Ctrl-Z on Windows). Of course, this may look remarkable like a hanging program. You can verify that this is, indeed, the problem by using a smaller size, e.g., 4. Of course, sizeof(infile) is nearly as good as a small random number: It is the size of an object of type std::ifstream and who can tell what that is? You probably meant to use sizeof(c) to make sure that the call to get(c, n) won't write more character than can fit into c.
Try this:
int cont = 0;
while(infile.good()) {
c[cont++] = infile.get();
}

How to read integer value from file in C++

How can read integer value from file? For example, these value present in a file:
5 6 7
If I open the file using fstream then how I can get integer value?
How can read that number and avoid blank space?
ifstream file;
file.open("text.txt");
int i;
while (file >> i) {
cout << i << endl;
}
ifstream f(filename);
int x, y, z;
f >> x >> y >> z;
ifstream f;
f.open("text.txt");
if (!f.is_open())
return;
std::vector<int> numbers;
int i;
while (f >> i) {
numbers.push_back(i);
}
It's really rare that anyone reads a file Byte by Byte ! ( one char has the size of one Byte).
One of the reason is that I/O operation are slowest. So do your IO once (reading or writing on/to the disk), then parse your data in memory as often and fastly as you want.
ifstream inoutfile;
inoutfile.open(filename)
std::string strFileContent;
if(inoutfile)
{
inoutfile >> strFileContent; // only one I/O
}
std::cout << strFileContent; // this is also one I/O
and if you want to parse strFileContent you can access it as an array of chars this ways: strFileContent.c_str()