How to split a read Text File into "\n"s? - c++

I need to split a text file into sentences, which are separated by moving to the next line.
Imagine this text:
Hey what's up
How are you doing?
Enjoy your coding!
This is the way I figured out to get the text from the file and save it:
ifstream file;
string text, finaltext;
file.open("input.txt", ios::in);
while(getline(file, text)){
finaltext += text;
}
cout<<finaltext;
So this actually does the job, but for a weird reason it Skips the "\n", and the result I get is this:
Hey what's upHow are you doing?Enjoy your coding!
So i need to find a new way to do this, making sure that finaltext gets the text separated by "\n"s. Can someone please help me? I'd be forever grateful. Thank you guys.

If you're getting each line seperately, you can try something like this:
file.open("input.txt", ios::in);
while (getline(file, text)) {
finaltext += text;
finaltext += "\n";
}
This way, you're adding the newline character yourself.

There is a difference between the functions ssize_t getline(char **restrict lineptr, size_t *restrict n, FILE *restrict stream) (which you get when you run man getline) and istream& getline (istream& is, string& str) which you are using. From the manpage of the first one:
getline() reads an entire line from stream, storing the address of the buffer containing the text into *lineptr. The buffer is null-terminated and includes the newline character, if one was found.
From the manpage of the second one:
If the delimiter is found, it is extracted and discarded (i.e. it is not stored and the next input operation will begin after it).
This might explain your confusion. So, as others have said, you'll just have to add it yourself.

Here you go, you just needed to concatenate '\n'
while (getline(file, text))
{
finaltext =finaltext + "\n" + text;
}
cout << finaltext;
As mentioned by Sandburg, + operator was almost deprecated with C++17 so you can use append() or insert() here.

Related

I cant end getline when see ' - ' character, can someone help me getline() ifstream in c++

ifstream InPut;
ofstream OutPut;
InPut.open("/Users/apple/Documents/Lập trình C++/OOP/Tập tin/Test1/Test1/FileIn.txt",ios_base::in);
string str, mssv;
getline(InPut,str);
InPut.seekg(1,ios_base::cur);
getline(InPut,mssv);
InPut.close();
cout<<""<<str<<"/"<<mssv;
return 0;
FileIn.txt:
Nguyen Xuan Sang-1520159
I just want to read "Nguyen Xuan Sang", but my code reads in all of FileIn.txt.
Computers can't read your mind. You never told it to read to the "-", so the computer has no way of knowing at all if you want to read until a space, line break, or something else.
getline() defaults to using a nextline as the delimiter, which in your case seems to cause it to read the whole file.
To tell getline() to read until a "-", specify the character as the third argument like this:
getline(InPut, str, '-');

string input copied text

I have for example the following piece of code:
string str;
int i;
cout<<"input:";
cin>>str;
cout<<"integer:";
cin>>i;
There is actually nothing wrong with this code, but if I paste some text into the command prompt in "input", it automatically fills some of the copied text into "integer". How can I solve this?
Edit: I can type texts as long as I want, but when I copy texts it goes wrong. I don't know why.
I guess, your text contains white spaces. So, std::cin will not work here. Use std::getline instead.
std::string str;
std::getline( std::cin, str );
There's a third parameter of std::getline - delimiter. By default, it's the new line char.
If your text does contain new line chars, than this will not work. You have 2 options:
find unique char, that may be used as delimiter and pass it as third parameter of std::getline
read line by line (using std::getline) from the user input (std::cin) and look for some special string, that will tell your program where the text ends. There's no other way to know where does the integer start (unless the text is with fixed size, but I doubt that)
string str;
int i;
cout<<"input:";
getline(cin, str);
// you want to read the whole line, operator>> will read until whitespace
cout<<"integer:";
cin>>i;

Problems using getline()

I'm running out of hair to pull out, so I thought maybe someone here could help me with this frustration.
I'm trying to read a file line by line, which seems simple enough, using getline(). Problem is, my code seems to keep ignoring the \n, and putting the entire file into one string, which is problematic to say the least.
void MakeRandomLayout(int rows, int cols)
{
string fiveByFive = "cubes25.txt";
string fourByFour = "cubes16.txt";
ifstream infile;
while (true) {
infile.open(fourByFour.c_str());
if (infile.fail()) {
infile.clear();
cout << "No such file found";
} else {
break;
}
}
Vector<string> cubes;
string cube;
while (std::getline(infile, cube)) {
cubes.add(cube);
}
}
Edits: Running OSX 10.7.
The infinite loop for the file is unfinished, will eventually ask for a file.
No luck with extended getline() version, tried that earlier.
Same system for dev and build/run.
The text file i'm reading in looks as follows:
AAEEGN
ABBJOO
ACHOPS
AFFKPS
AOOTTW
CIMOTU
DEILRX
DELRVY
DISTTY
EEGHNW
EEINSU
EHRTVW
EIOSST
ELRTTY
HIMNQU
HLNNRZ
Each string is on a new line in the file. The second one that I'm not reading in is the same but 25 lines instead of 16
Mac software recognizes either '\r' or '\n' as line-endings, for backward compatibility with Mac OS Classic. Make sure that your text editor hasn't put '\r' line endings in your file when your processing code is expecting '\n' (and verify that the '\n' characters you think are in the middle of the string aren't in fact '\r' instead.
I suspect that you are failing to display the contents of Vector correctly. When you dump the Vector, do you print a \n after each entry? You should, because getline discards the newlines on input.
FYI: the typical pattern for reading line-by-line is this:
Vector<string> cubes;
string cube;
while(std::getline(infile, cube)) {
cubes.add(cube);
}
Note that this will discard the newlines, but will put one line per entry in Vector.
EDIT: For whatever it is worth, if you were using an std::vector, you could slurp the file in thusly:
std::ifstream ifile(av[1]);
std::vector<std::string> v(
(std::istream_iterator<std::string>(ifile)),
std::istream_iterator<std::string>());

Read number of lines, words, characters from a file

I can read the number of lines easy, using:
ifstream in(file);
string content;
while(getline(in, content))
{
// do stuff
}
Or I can read the number of words and characters easy using something like:
ifstream in(file)
string content;
int numOfCharacters = 0;
int numOfWords = 0;
while(in >> content)
{
++numOfWords;
numOfCharacters += content.size();
}
But I dont want to read the file twice. How can I read the file once, and find out the number of lines, words and characters?
PS: I would welcome a Boost sugestion, if there is a easy way.
Thank you.
Read the line and for each line count the words. See stringstream for the second part.
(I'm not giving more information, that looks too much like an homework).
This could be done with a trivial boost.spirit.qi parser.
Sticking with the iostreams solution: you could create a strstream out of each line read via getline(), and do the word/char counting operations on it, accumulating across all the lines.

C++: Why does space always terminate a string when read?

Using type std::string to accept a sentence, for practice (I haven't worked with strings in C++ much) I'm checking if a character is a vowel or not. I got this:
for(i = 0; i <= analyse.length(); i++) {
if(analyse[i] == 'a' || analyse[i] == 'e' [..etc..]) {
...vowels++;
} else { ...
...consonants++;
}
This works fine if the string is all one word, but the second I add a space (IE: aeio aatest) it will only count the first block and count the space as a consonant, and quit reading the sentence (exiting the for loop or something).
Does a space count as no character == null? Or some oddity with std::string?, It would be helpful to know why that is happening!
EDIT:
I'm simply accepting the string through std::cin, such as:
std::string analyse = "";
std::cin >> analyse;
I'd guess you're reading your string with something like your_stream >> your_string;. Operator >> for strings is defined to work (about) the same as scanf's %s conversion, which reads up until it encounters whitespace -- therefore, operator>> does the same.
You can read an entire line of input instead with std::getline. You might also want to look at an answer I posted to a previous question (provides some alternatives to std::getline).
I can't tell from the code that you have pasted, but I'm going to go out on a limb and guess that you're reading into the string using the stream extraction operator (stream >> string).
The stream extraction operator stops when it encounters whitespace.
If this isn't what's going on, can you show us how you're populating your string, and what its contents are?
If I'm right, then you're going to want a different method of reading content into the string. std::getline() is probably the easiest method of reading from a file. It stops at newlines instead of at whitespace.
Edit based on edited question:
use this (doublecheck the syntax. I'm not in front of my compiler.):
std::getline(std::cin, analyze);
This ought to stop reading when you press "enter".
If you want to read in an entire line (including the blanks) then you should read using getline. Schematically it looks like this:
#include <string>
istream& std::getline( istream& is, string& s );
To read the whole line you do something like this:
string s;
getline( cin, s );
cout << "You entered " << s << endl;
PS: the word is "consonant", not "consenent".
The >> operator on an istream separates strings on whitespace. If you want to get a whole line, you can use readline(cin,destination_string).