How to read character from file c++ - c++

Is there something like fgetc in c++? File contains 3 words "send more money" and I need to solve a task where each letter represents a number(money is the answer(:D) and I add send+more), thats why I want to read each string as char array, but now I'm struggling to do so, the only info that I got is how to read everything between spaces. So, is there something like fgetc was in c or should I rethink how to do this task?
(sorry if I will be slow to respond have to go to sleep)

There's always std::istream::get(), which works exactly like
fgetc. More idiomatic in C++ might be to use
std::istream::get(char&), which stores the results directly
into a char (rather than returning an int, which must be
checked for EOF before converting it to a char), and
signals end of file or an error in the usual way.

istream/fstream have a get function that will return characters

Related

How to pass array of strings to a main()

I have not been successful on searching for this topic. I want to pass an array of strings to a C++ console app. The closest I have found is using argv(), but the number (variable) may be 50 strings which would be ugly on the calling side.
Is it possible to pass an array, or a structure to main()? I am totally open to which way to go, I have almost no experience with interprocess communication.
The conventional approach is just STDIN, as then you can send in whatever using pipes or redirection. As in: program < input
The second option is your first argument is a file to read this data from. As in program input.file
There are conventions that accommodate both, like where - as a filename is presumed to mean "read STDIN", or where no filename given means read from STDIN (e.g. grep), so you can have it both ways.
If your strings contain newlines which complicate framing you may want to use a format like INI, JSON, or YAML to read in the data.

How to read .inp file in c++?

I have a dataset, a ".inp" format file, and I need to read this file in c++. However, the fopen() fread() method seemed to fail and read the wrong data(e.g. the first integer should be 262144, the fread yields an integer much larger than this nevertheless).
To be more specific, my ".inp" file contains a few integers and float points, how can I read them successfully in c++?
enter image description here
This is the screenshot of the "*.inp" file from Notepad++. Basically this is a text file.
I solved it by coping the data into a txt. However, I am still not aware how to read "*.inp"
I found some info about INP file extension. It seems like there are multiple variances of it, each meant to be used for different purpose. Where is your file coming from? As for soultion, if you can't open the file using fopen/fstream normally, you could treat it as binary and read each value in the way you specify. Other than that, I could think of calling system functions to get file contents (like cat in linux for example), then if there are some random characters, you could parse your string to ommit them.
Here is example of how to call cat in C++:
Simple way to call 'cat' from c++?

C++ How can I retrieve a file BOM to get its type of encoding?

I don't know if its possible, but is there a way to retrieve the first 4 bytes of a file (most likely the BOM) in order to get its type of encoding (UTF-8, UTF-16LE, CP1252, etc...). And then, if the file selected was encoded in UTF-8, the values found in an array "tabBytes[]" would be something like:
tabBytes[0] = 0xEF
tabBytes[1] = 0xBB
tabBytes[2] = 0xBF
tabBytes[3] = XXXX
Thanks for taking time and helping me! I'll be looking forward to read your comments and answers on this.
EDIT: I'm new to C++, so the code I wrote before is probably wrong, thus I removed it.
FINAL EDIT: Finally I found a solution to my problem, thanks to those who helped me!
Array indices start at 0, so you're writing past the end of the buffer with buffer[fourBytes] = '\0';. You need to allocate fourBytes + 1 bytes if you want to do that. This should stop the crash you're getting when you delete the buffer.
However the only reason for null-terminating the buffer like that is if you want to treat it as a C-style string (e.g. to print it out), which you don't seem to be doing. You're copying it into tabBytes, but you're not copying the null-terminator. So it's unclear exactly what it is you're trying to achieve.
Your overall logic for reading the first few bytes from the file is fine. Although based on the code above, you could just read the data straight into tabBytes and do away with the allocation/copy/free of buffer.

getline() text with UNIX formatting characters

I am writing a C++ program which reads lines of text from a .txt file. Unfortunately the text file is generated by a twenty-something year old UNIX program and it contains a lot of bizarre formatting characters.
The first few lines of the file are plain, English text and these are read with no problems. However, whenever a line contains one or more of these strange characters mixed in with the text, that entire line is read as characters and the data is lost.
The really confusing part is that if I manually delete the first couple of lines so that the very first character in the file is one of these unusual characters, then everything in the file is read perfectly. The unusual characters obviously just display as little ascii squiggles -arrows, smiley faces etc, which is fine. It seems as though a decision is being made automatically, without my knowledge or consent, based on the first line read.
Based on some googling, I suspected that the issue might be with the locale, but according to the visual studio debugger, the locale property of the ifstream object is "C" in both scenarios.
The code which reads the data is as follows:
//Function to open file at location specified by inFilePath, load and process data
int OpenFile(const char* inFilePath)
{
string line;
ifstream codeFile;
//open text file
codeFile.open(inFilePath,ios::in);
//read file line by line
while ( codeFile.good() )
{
getline(codeFile,line);
//check non-zero length
if (line != "")
ProcessLine(&line[0]);
}
//close line
codeFile.close();
return 1;
}
If anyone has any suggestions as to what might be going on or how to fix it, they would be very welcome.
From reading about your issues it sounds like you are reading in binary data, which will cause getline() to throw out content or simply skip over the line.
You have a couple of choices:
If you simply need lines from the data file you can first sanitise them by removing all non-printable characters (that is the "official" name for those weird ascii characters). On UNIX a tool such as strings would help you with that process.
You can off course also do this programmatically in your code by simply reading in X amount of data, storing it in a string, and then removing those characters that fall outside of the standard ASCII character range. This will most likely cause you to lose any unicode that may be stored in the file.
You change your program to understand the format and basically write a parser that allows you to parse the document in a more sane way.
If you can, I would suggest trying solution number 1, simply to see if the results are sane and can still be used. You mention that this is medical data, do you per-chance know what file format this is? If you are trying to find out and have access to a unix/linux machine you can use the utility file and maybe it can give you a clue (worst case it will tell you it is simply data).
If possible try getting a "clean" file that you can post the hex dump of so that we can try to provide better help than that what we are currently providing. With clean I mean that there is no personally identifying information in the file.
For number 2, open the file in binary mode. You mentioned using Windows, binary and non-binary files in std::fstream objects are handled differently, whereas on UNIX systems this is not the case (on most systems, I'm sure I'll get a comment regarding the one system that doesn't match this description).
codeFile.open(inFilePath,ios::in);
would become
codeFile.open(inFilePath, ios::in | ios::binary);
Instead of getline() you will want to become intimately familiar with .read() which will allow unformatted operations on the ifstream.
Reading will be like this:
// This code has not been tested!
char input[1024];
codeFile.read(input, 1024);
int actual_read = codeFile.gcount();
// Here you can process input, up to a maximum of actual_read characters.
//ProcessLine() // We didn't necessarily read a line!
ProcessData(input, actual_read);
The other thing as mentioned is that you can change the locale for the current stream and change the separator it considers a new line, maybe this will fix your issue without requiring to use the unformatted operators:
imbue the stream with a new locale that only knows about the newline. This method may or may not let your getline() function without issues.

C++ new line not translating

First off, I'm a complete beginner at C++.
I'm coding something using an API, and would like to pass text containing new lines to it, and have it print out the new lines at the other end.
If I hardcode whatever I want it to print out, like so
printInApp("Hello\nWorld");
it does come out as separate lines in the other end, but if I retrieve the text from the app using a method that returns a const char then pass it straight to printInApp (which takes const char as argument), it comes out as a single line.
Why's this and how would I go about to fix it?
It is the compiler that process escape codes in string literals, not the runtime methods. This is why you can for example have "char c = '\n';" since the compiler just compiles it as "char c = 10".
If you want to process escape codes in strings such as '\' and 'n' as separate characters (eg read as such from a file), you will need to write (or use an existing one) a string function which finds the escape codes and converts them to other values, eg converting a '\' followed by a 'n' into a newline (ascii value 10).