I cant end getline when see ' - ' character, can someone help me getline() ifstream in c++ - 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, '-');

Related

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

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.

C++: Getline stops reading at first whitespace

Basically my issue is that I'm trying to read in data from a .txt file that's full of numbers and comments and store each line into a string vector, but my getline function stops reading at the first whitespace character so a comment like (* comment *) gets broken up into
str[0] = "(*";
str[1] = "comment";
str[2] = "*)";
This is what my codeblock for the getline function looks like:
int main() {
string line;
string fileName;
cout << "Enter the name of the file to be read: ";
cin >> fileName;
ifstream inFile{fileName};
istream_iterator<string> infile_begin {inFile};
istream_iterator<string> eof{};
vector<string> data {infile_begin, eof};
while (getline(inFile, line))
{
data.push_back(line);
}
And this is what the .txt file looks like:
101481
10974
1013
(* comment *) 0
28292
35040
35372
0000
7155
7284
96110
26175
I can't figure out why it's not reading the whole line.
This is for the very simple reason that your code is not using std::getline to read the input file.
If you look at your code very carefully, you will see that before you even get to that point, your code constructs an istream_iterator<string> on the file, and by passing it, and the ending istream_iterator<string> value to the vector's constructor, this effectively swallows the entire file, one whitespace-delimited word at a time, into the vector.
And by the time things get around to the getline loop, the entire file has already been read, and the loop does absolutely nothing. Your getline isn't really doing anything, with the current state of affairs.
Get rid of that stuff that involves istream_iterators, completely, and simply let getline do the job it was intended for.

How to NOT use \n as delimiter in getline()

I'm trying to read in lines from a plain text file, but there are line breaks in the middle of sentences, so getline() reads until a line break as well as until a period. The text file looks like:
then he come tiptoeing down and stood right between us. we could
a touched him nearly. well likely it was minutes and minutes that
there warnt a sound and we all there so close together. there was a
place on my ankle that got to itching but i dasnt scratch it.
My read-in code:
// read in sentences
while (file)
{
string s, record;
if (!getline( file, s )) break;
istringstream ss(s);
while (ss)
{
string s;
if (!getline(ss, s, '.')) break;
record = s;
if(record[0] == ' ')
record.erase(record.begin());
sentences.push_back(record);
}
}
// output sentences
for (vector<string>::size_type i = 0; i < sentences.size(); i++)
cout << sentences[i] << "[][][][]" << endl;
The purpose of the [ ][ ][ ][ ] was to check if linebreaks were used as delimiters and were not just being read into the string. The output would look like:
then he come tiptoeing down and stood right between us.[][][][]
we could[][][][]
a touched him nearly.[][][][]
well likely it was minutes and minutes that[][][][]
there warnt a sound and we all there so close together.[][][][]
there was a[][][][]
place on my ankle that got to itching but i dasnt scratch it.[][][][]
What exactly is your question?
You're using getline() to read from the file stream with a newline delimiter, then parsing that line with a getline() using the istringstream is and a delimiter '.'. So of course you're getting your strings broken at both the new line and the '.'.
getdelim() works like getline(), except that a line delimiter other than newline can be specified as the delimiter argument. As with getline(), a delimiter character is not added if one was not present in the input before end of file was reached.
ssize_t getdelim(char **restrict lineptr, size_t *restrict n, int delimiter, FILE *restrict stream);

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;

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).