C++ read accented characters via ifsteam or cin - c++

So I'm a starter in C++, and I wanted to somehow get in text with accented characters.
I've read documentations, other questions, but none of them worked for me.
And I don't really understand it. Here is the file, and the output.
Text file:
abc
def
árvíztűrő tükörfúrógép
Console output:
abc
def
árvĂ­ztĹ+rĹ' tĂĽkörfĂşrĂłgĂcp
Somebody please help me, how can I get the same text on the console, as in the file?
And could somebody explain to me, whats going on here? ( i.e. what are SetLocale() and .imbue() )
Thank you for help!
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <locale>
int main()
{
setlocale(LC_ALL, "");
std::string txt;
std::ifstream fstream;
fstream.open("C:\\Dev\\alma.txt");
fstream.imbue(std::locale(""));
while (getline(fstream, txt))
{
std::cout << txt << "\n";
}
std::cout << "\n";
fstream.close();
}

Related

fstream not working properly with russian text?

I work with russian a lot and I've been trying to get data from a file with an input stream. Here's the code, it's supposed to output only the words that contain no more than 5 characters.
#include <iostream>
#include <fstream>
#include <string>
#include <Windows.h>
using namespace std;
int main()
{
setlocale(LC_ALL, "ru_ru.utf8");
ifstream input{ "in_text.txt" };
if (!input) {
cerr << "Ошибка при открытии файла" << endl;
return 1;
}
cout << "Вывод содержимого файла: " << "\n\n";
string line{};
while (input >> line) {
if (line.size() <= 5)
cout << line << endl;
}
cout << endl;
input.close();
return 0;
}
Here's the problem:
I noticed the output didn't pick up all of the words that were actually containing less than 5 characters. So I did a simple test with the word "Test" in english and the translation "тест" in russian, the same number of characters. So my text file would look like this:
Test тест
I used to debugger to see how the program would run and it printed out the english word and left the russian. I can't understand why this is happening.
P.S. When I changed the code to if (line.size() <= 8) it printed out both of them. Very odd
I think I messed up my system locale somehow I don't know. I did one time try to use std::locale
without really understanding it, maybe that did something to my PC I'm not really sure. Please help
I'm very unsure about this but using codecvt_utf8 and wstring_convert seems to work:
#include <codecvt> // codecvt_utf8
#include <string>
#include <iostream>
#include <locale> // std::wstring_convert
int main() {
// ...
while (input >> line) {
// convert the utf8 encoded `line` to utf32 encoding:
std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> u8_to_u32;
std::u32string u32s = u8_to_u32.from_bytes(line);
if (u32s.size() <= 5) // check the utf32 length
std::cout << line << '\n'; // but print the utf8 encoded string
}
// ...
}
Demo

After adding a function to use a renamed file, the program won't find the text string anymore

Okay, the title may be a bit vague. I honestly don't even know how to phrase the question.
The program tries to find a string of text inside a file, and then
print the entire line that the string is on.
While testing, I created a file with the string I wanted to find as the only contents of the file:
#include <Windows.h>
#include <iostream>
#include <fstream>
#include <string>
#include <iostream>
#include <filesystem>
#include <Wininet.h>
#include <stdio.h>
//...
std::cout << "Creating a document...\n"; //this is test code that creates a sample document with "string" inside it.
std::ofstream write;
write.open ("test.txt"); //actual file creation
write << "[TEMPORARY]string[TEST]\n"; //print into the document
write.close();
std::cout << "Document created.\n"; //end message
When I use this configuration, the program finds "string" and outputs
[TEMPORARY]string[TEST] as expected.
However, this layout was only to be used in testing, so after confirming it worked, I wanted to test renaming the file that I would actually be using in order to find the same string.
I copied the file, and wrote a program to rename it to a text file so it would be easier to read from:
#include <Windows.h>
#include <iostream>
#include <fstream>
#include <string>
#include <iostream>
#include <filesystem>
#include <Wininet.h>
#include <stdio.h>
//...
std::cout << "Changing extension to txt...\n";
//int result; //making variable to store result of following code. potential warning fix.
char oldname[] = "data.ldb"; //set up rename variables
char newname[] = "string.txt"; //same as ^
rename(oldname, newname); //change the ldb to txt so we can read from it.
std::cout << "Extension changed.\n"; //this code block produces a warning. please fix. low priority.
If changing ldb to txt is a stupid idea and won't work, let me know of any workarounds.
After I did this, the program does not find the string. Opening the file with notepad as an ldb or a txt shows the string exists.
#include <Windows.h>
#include <iostream>
#include <fstream>
#include <string>
#include <iostream>
#include <filesystem>
#include <Wininet.h>
#include <stdio.h>
//...
std::cout << "Attempting to get line with word \"string...\"\n";
std::ifstream input; //"input" is what we are using to read the file.
size_t pos; //size_t has something to do with finding text.
std::string line; //this is what we save the line to.
input.open("string.txt"); //open the document with the string.
if (input.is_open()) { //if we are in the file...
while (!input.eof()) { //get a line from it..."
getline(input, line);
pos = line.find("string"); //that says "string."
if (pos != std::string::npos) { //if we find it...
std::cout << "Line found!" //print "Line found!"
" \n" //(this is to remove the "i couldn't find it" message.)
"The line is...\n\n";
std::cout << line; //and then print the line we found.
std::cout << "\n\nSaving to file...\n";
std::ofstream grab; //now open a new file...
grab.open("grabbedstring.txt"); //called "grabbedstring,"
grab << line; //print the line to it,
grab.close(); //and close the file.
std::cout << "Saved to file \"grabbedstring.txt"; //We did it! :D
}
else {
std::cout << "I couldn't find it, sorry.\n" //we didn't do it... D:
"\x1b[A";
}
}
}
else {
std::cout << "I couldn't open the file, sorry.\n"; //we didn't even come close... ;-;
}
input.close();
std::cout << "\n\nEnd of code so far.\n"
"Completed successfully!\n";
system("pause");
The program outputs "I couldn't find it, sorry.\n".
Honestly, I think it has something to do with the file conversion as it works with a text file created within the program itself, but i don't see much wiggle room there.
When I open the new text file in a text editor after the program fails, it works just fine.
EDIT:
After further testing, this might be situational. I created a sample ldb file with a string in it, and it worked. I tried pushing it way down to the bottom and it worked. I tried the original file, and it doesn't. it might actually just be unable to print some of the characters that are in the file. This may require a very complicated workaround, and it may even be impossible; or, it could be simple...I don't know. I will conduct further testing and if I solve the problem I will close the question.
It also doesn't save to the document, so it must be a problem within the if statement.
EDIT2: updated code, still not working. further testing concludes it might be a problem with the way the source file... well... is. it might be too long, it might be too complex, it might be impossible. i am seriously puzzled with this one. the code works fine in any other situation, so if you need something similar feel free to grab this and use it while i try and make it work for what I need.
oh yeah and thanks for the formatting, casey.

Reading input from a text file and outputting the text to the screen in c++

I'm a new student of the c++ language and I'm having trouble understanding...well, frankly, a whole lot of things. I've been given this assignment to read text from a text file and output it to the screen, and I'm having quite a bit of trouble. I've spent several hours on this now already researching and testing, and this is the code that I've got so far, and it's not working, and I'm not really sure why. Any and all help or insights anyone would be willing to share with me would be very much appreciated. I'm sorry I don't recall all the errors I've encountered as I worked on this by name...but I assure you there were plenty of them. Like trying to use "fopen" in my compiler...it didn't like that, so I tried "fopen_s" like it suggested, but then it said that it wouldn't accept any arguments anymore...then I found that I needed to add "#define _CRT_SECURE_NO_DEPRECATE" as a header(?) file at the top of the program, and that problem did get solved and the program actually compiled...but then it gave me a fatal error, not sure what I did that was so fatal, but there you are. Please help.
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *pf;
char ch;
pf = fopen("C:\\lowerCase\anyOldTextFile.txt", "r");
feof(pf);
if (pf == NULL)
{
printf("Unable to open the file.\n");
}
else
{
while (!feof(pf))
{
ch = fgetc(pf);
printf("%c", ch);
}
fclose(pf);
}
system("pause");
}
Try this, which I pasted from this site:
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
I didn't test this code, but it looks fine. They also explain the code on the website. I suggest visiting that page and reading all of it. Then you should be able to understand how this is working.

getline() not reading first lines

I am c++ beginner and this is for school..
I am trying to read a file about 28kb big. The program works but it doesnt print the first 41 lines. It works fine with a smaller file.
At first i was reading into a char array and switch it to strings.
i also tried changing the log buffer but it apparently it should be big enough..
I feel like this should be very simple, but just cant figure it out..
Any help will be greatly apreciated..
Thanks!
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstdio>
#include <cerrno>
using namespace std;
struct espion
{
char nom[30];
char pays[20];
char emploi[29];
};
int main()
{
const int MAX_NOM = 30, MAX_PAYS = 20, MAX_EMPLOI = 29;
char nomFichier[50] = "espion.txt";
ifstream aLire;
aLire.open(nomFichier, ios::in|ios::binary);
if(!aLire.is_open()){
exit(EXIT_FAILURE);
}
std::string infoEspion;
while(aLire)
{
infoEspion.clear();
std::getline(aLire, infoEspion);
cout << infoEspion ;
}
aLire.close();
system("pause");
return 0;
}
From the system("pause"), it looks like you're running on Windows. With ios::binary, the end-of-line marker is not translated, and the cout << infoEspion; statement prints these "raw" lines in such a way that all of the lines are written on top of each other. (More specifically, each line will end with a return but no newline, so the cursor goes back to the start of the same line after executing each cout statement.) If you take out the ios::binary, you will echo all of the input on a single, very long line. Changing the statement to cout << infoEspion << endl; will echo all of the lines.

Trouble reading .csv files in C++

I am working on a project where I intend on connecting to a database, grabbing a .csv file, reading it, manipulating the data and then returning it back to the database. Fairly simple and straight forward but I am still learning so if any one could point me in the right direction I would greatly appreciate it. Right now I have a simple program that is trying to read a .csv file and return the values to me printed on the console. I have been trying to find some good online resources for this but have came up short. Here is my code for what I have stumbled through so far.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
int loop = 1;
while(loop = 1)
{
cout << "Welcome! " << endl;
ifstream myfile;
myfile.open ("..\\ Source\External\\ Sample.csv", ifstream::in);
The real path to this file is C:\Documents and Settings\RHatfield\My Documents\C++\Product Catalog Creator\Source\External\Sample.csv
while (myfile.good())
cout << (char) myfile.get();
myfile.close();
system("PAUSE");
return 0;
}
}
Now the issue is it does not print the values so I do not know that they are properly being captured. I have a feeling it is my file path but that's the only way I can find to write it without it throwing errors. I think it's something with the spaces in the file path but I can't seem to find another way to make it work. I am not looking for a handout and this is not homework or just regular work. I am trying to learn and having trouble teaching myself so if someone knows what the issue is and can help me fix it or even point me to a relevant article online would be greatly appreciated.
Try the following code. I think the problem was you were making an assignment statement in the while condition statement.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
cout << "Welcome! " << endl;
ifstream myfile;
myfile.open ("C:\\Documents and Settings\\RHatfield\\My Documents\\C++\\Product Catalog Creator\\Source\\External\\Sample.csv", ifstream::in);
while (myfile.good())
cout << (char) myfile.get();
myfile.close();
system("PAUSE");
return 0;
}