getline() not reading first lines - c++

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.

Related

How to read a mdash character in C++ fstream

I currently am trying to have my program read a text document of the Gettysburg address and print it out into the command prompt. The issue I have ran into is are — (mdashs) in the text that the program is printing out as ΓÇö. I attempted to add a part of the code to read for the mdash but it does not ever come back as a mdash so it never changes what to be printed. Here is what I have so far.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char asciiChar;
ifstream readChar;
readChar.open("Gettysburg.txt");
while(!readChar.eof())
{
readChar.get(asciiChar);
if (!readChar.eof()){
if (asciiChar!='—'){
cout << asciiChar;
}
if (asciiChar=='—'){
asciiChar=151;
cout << asciiChar;
}
}
}
readChar.close();
return 0;
}
Any help on how to properly detect this value would be appreciated!

Printing out blank spaces from a text file in C++

#include <iostream>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <string>
#include <iomanip>
#include <fstream>
#include <stdio.h>
using namespace std;
int main()
{
ifstream file;
string filename;
char character;
int letters[153] = {};
cout << "Enter text file name: ";
cin >> filename;
file.open(filename.c_str());
if (! file.is_open())
{
cout << "Error opening file. Check file name. Exiting program." << endl;
exit(0);
}
while (file.peek() != EOF)
{
file >> character;
if(!file.fail())
{
letters[static_cast<int>(character)]++;
}
}
for (int i = 0; i <= 153; i++)
{
if (letters[i] > 0)
{
cout << static_cast<char>(i) << " " << letters[i] << endl;
}
}
exit(0);
}
#endif
Hi everyone, my current code counts the frequency of each letter from a text file. However, it does not count the number of blank spaces. Is there a simple way to printout the number of blank spaces in a .txt file?
Also, how come when I'm trying to access a vector item, I run into a seg fault?
For example, if I use:
cout << " " + letters[i] << endl;, it displays a segfault. Any ideas?
Thank you so much.
By default, iostreams formatted input extraction operations (those using >>) skip past all whitespace characters to get to the first non-whitespace character. Perhaps surprisingly, this includes the extraction operator for char. In order to consider whitespace characters as characters to be processed as usual, you should alter use the noskipws manipulator before processing:
file << std::noskipws;
Don't forget to set it back on later:
file << std::skipws;
What if you're one of those crazy people who wants to make a function that leaves this aspect (or in even all aspects) of the stream state as it was before it exits? Naturally, C++ provides a discouragingly ugly way to achieve this:
std::ios_base::fmtflags old_fmt = file.flags();
file << std::noskipws;
... // Do your thang
file.flags(old_fmt);
I'm only posting this as an alternative way of doing what you're apparently trying. This uses the same lookup table approach you use in your code, but uses an istreambuf_iterator for slurping unformatted (and unfiltered) raw characters out of the stream buffer directly.
#include <iostream>
#include <fstream>
#include <iterator>
#include <climits>
int main(int argc, char *argv[])
{
if (argc < 2)
return EXIT_FAILURE;
std::ifstream inf(argv[1]);
std::istreambuf_iterator<char> it_inf(inf), it_eof;
unsigned int arr[1 << CHAR_BIT] = {};
std::for_each(it_inf, it_eof,
[&arr](char c){ ++arr[static_cast<unsigned int>(c)];});
for (int i=0;i<sizeof(arr)/sizeof(arr[0]);++i)
{
if (std::isprint(i) && arr[i])
std::cout << static_cast<char>(i) << ':' << arr[i] << std::endl;
}
return 0;
}
Executing this on the very source code file itself, (i.e. the code above) generates the following:
:124
#:4
&:3
':2
(:13
):13
*:1
+:4
,:4
/:1
0:3
1:2
2:1
::13
;:10
<:19
=:2
>:7
A:2
B:1
C:1
E:2
F:1
H:1
I:3
L:1
R:2
T:2
U:1
X:1
[:8
]:8
_:10
a:27
b:1
c:19
d:13
e:20
f:15
g:6
h:5
i:42
l:6
m:6
n:22
o:10
p:1
r:37
s:20
t:34
u:10
v:2
z:2
{:4
}:4
Just a different way to do it, but hopefully it is clear that usually the C++ standard library offers up elegant ways to do what you desire if you dig deep enough to find whats in there. Wishing you good luck.

the output is not what i typed.It is --> (畳慨汩朠灵慴찀쳌쳌쳌)

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
char x[20];
cout << "enter something\n";
cin.getline(x,20);
ofstream o("d:/tester.txt");
//o.write( (char*)&x , sizeof(x) );
for(int i = 0 ; i<=19 ; i++ ) {
o.put(x[i]);
}
}
I am not getting that output in the file the one which i enter during program . for eg. the output is 畳慨汩朠灵慴찀쳌쳌쳌 on writing suhail gupta.
What is the problem with the code ? Even when i use o.write( (char*)&x , sizeof(x) ); (the commented statement) i get the same output.
What is the reason?
Your program involves undefined behavior. The x array is not fully initialized and you read from the uninitialized indices. Besides, you always write 20 bytes, independent of what you read from the user.
I guess you use some text editor like Notepad. The latter has bugs when trying to guess the encoding. It appears that it guesses the file is UTF16 and displays 20/2 == 10 characters instead.
To solve the problem, store to the file exactly the number of characters entered by the user. Use std::string to make it easier.
Edit: The C++ way:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string x;
cout << "enter something\n";
getline(cin, x);
ofstream o("d:/tester.txt");
o << x;
}

First character disappearing in ifstream

Why does this code print the char, without first character?? It says ocalhost instead of localhost. Grateful for help.
#include <winsock2.h>
#include <mysql/mysql.h>
#include <iostream>
#include <windows.h>
#include <fstream>
using namespace std;
int main () {
int b = 0;
char * pch;
int stringLength = 0;
char textRead[50];
ifstream infile("config.ini", ios::in | ios::binary);
if(!infile) {
cout << "ERROR: config.ini not found!\n";
system("pause");
exit(0);
}
infile >> textRead;
stringLength = strlen(textRead);
pch=strchr(textRead,'"');
while(pch != NULL) {
infile.seekg(pch-textRead-1);
infile >> textRead;
pch = strchr(pch+1,'"');
}
cout << textRead;
infile.close();
Inside your while loop you call:
infile >> textRead;
pch = strchr(pch+1,'"');
When you try to run strchr in the second line, it's still referring back to the previous string you had in textRead NOT the most recently extracted word.
Unfortunately I can't deduce what you're actually trying to do so I can't offer suggestions on how to fix it.
I'm guessing at the contents of config.ini, since you didn't provide it, but it looks like the ifstream is reading just fine. put a cout << textRead << endl; after your infile >> textRead; to check. This is what I'm using for config.ini:
localhost = "foo"
Your logic with seekg and friends seems broken, though. seekg isn't meant to be used to support parsing (in your case, skipping quotes); it's meant to skip over large chunks of file when needed so you don't waste time reading it in. Honestly, I'm not sure what you're doing since pch-textRead-1 could be -1 if the first character is a quote.
Another thing is that infile >> textRead; does not read a line, it reads a word, and discards leading whitespace.
For the record, I omitted
#include <winsock2.h>
#include <mysql/mysql.h>
#include <windows.h>
since it isn't needed.

Most Compact Way to Count Number of Lines in a File in C++

What's the most compact way to compute the number of lines of a file?
I need this information to create/initialize a matrix data structure.
Later I have to go through the file again and store the information inside a matrix.
Update: Based on Dave Gamble's. But why this doesn't compile?
Note that the file could be very large. So I try to avoid using container
to save memory.
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
using namespace std;
int main ( int arg_count, char *arg_vec[] ) {
if (arg_count !=2 ) {
cerr << "expected one argument" << endl;
return EXIT_FAILURE;
}
string line;
ifstream myfile (arg_vec[1]);
FILE *f=fopen(myfile,"rb");
int c=0,b;
while ((b=fgetc(f))!=EOF) c+=(b==10)?1:0;
fseek(f,0,SEEK_SET);
return 0;
}
I think this might do it...
std::ifstream file(f);
int n = std::count(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), '\n') + 1;
If the reason you need to "go back again" is because you cannot continue without the size, try re-ordering your setup.
That is, read through the file, storing each line in a std::vector<string> or something. Then you have the size, along with the lines in the file:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
int main(void)
{
std::fstream file("main.cpp");
std::vector<std::string> fileData;
// read in each line
std::string dummy;
while (getline(file, dummy))
{
fileData.push_back(dummy);
}
// and size is available, along with the file
// being in memory (faster than hard drive)
size_t fileLines = fileData.size();
std::cout << "Number of lines: " << fileLines << std::endl;
}
Here is a solution without the container:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
int main(void)
{
std::fstream file("main.cpp");
size_t fileLines = 0;
// read in each line
std::string dummy;
while (getline(file, dummy))
{
++fileLines;
}
std::cout << "Number of lines: " << fileLines << std::endl;
}
Though I doubt that's the most efficient way. The benefit of this method was the ability to store the lines in memory as you went.
FILE *f=fopen(filename,"rb");
int c=0,b;while ((b=fgetc(f))!=EOF) c+=(b==10)?1:0;fseek(f,0,SEEK_SET);
Answer in c.
That kind of compact?
#include <stdlib.h>
int main(void) { system("wc -l plainfile.txt"); }
Count the number of instances of '\n'. This works for *nix (\n) and DOS/Windows (\r\n) line endings, but not for old-skool Mac (System 9 or maybe before that), which used just \r. I've never seen a case come up with just \r as line endings, so I wouldn't worry about it unless you know it's going to be an issue.
Edit: If your input is not ASCII, then you could run into encoding problems as well. What's your input look like?