How can I get a word from string - c++

I have f.e. "I am working as a nurse."
How Can I or which function use to get word from letter number 1 to space or to letter number 11?
So should I get " am working "

To read a word from a stream use operator>> on a string
std::stringstream stream("I am working as a nurse.");
std::string word;
stream >> word; // word now holds 'I'
stream >> word; // word now holds 'am'
stream >> word; // word now holds 'working'
// .. etc

It is not totally clear what you want, but from your example it seems like you want the substring that starts at character 1 and ends on the character 11 places later (that's 12 characters total). That means you want string::substr:
std::string str("I am working as a nurse");
std::string sub = str.substr(1,12);

char[] source = "I am working as a nurse."
char[11] dest;
strncpy(dest, &source[1], 10)

Related

Switching from formatted to unformatted input in C++

I have an input text file. The first line has two int numbers a and b, and the second line is a string. I want to use formatted input to do file >> a >> b, and then unformatted input to get the characters of the string one by one. In between the two steps, I need to skip over the '\n' character at the end of the first line. I used
while(file.get()<=' ' && !file.eof()); // skip all unprintable chars
if(!file.eof()) file.unget(); // keep the eof sign once triggered
to make the input format more flexible. The user can now separate the numbers a and b from the string using an arbitrary number of empty lines '\n', tab keys '\t', and/or space keys ' ' -- the same freedom he has to separate the numbers a and b. There's even no problem reading in Linux a text file copied from Windows when every end of line now becomes "\r\n".
Is there an ifstream function that does the same thing (skip all chars <=' ' until the next printable char or EOF is reached)? The ignore function does not seem to do that.
Yes, there is: std::ws manipulator. It skips whitespace characters until a non-whitespace is found or end of stream is reached.. It is similar to use of whitespace character in scanf format string.
In fact, it is used by formatted input before actually starting to parse characters.
You can use it like that:
int x;
std::string str;
std::cin >> x >> std::ws;
std::getline(std::cin, str);
//...
//std::vector<int> vec;
for(auto& e: vec) {
std::cin >> e;
}
std::getline(std::cin >> std::ws, str);

Using getline on a string

How can I use getline() to read words form a line that I have stored in a string?
For example:
char ch[100],w[20];
cin.getline(ch,100);
Now can I use getline to count the number of words in ch? I don't want to use a delimiter to directly count words from ch. I want to read words from ch and store them in w.
I have tried using ch in getline as a parameter.
getline is implemented in the standard as either a stream method, or a string method which takes a stream: http://en.cppreference.com/w/cpp/string/basic_string/getline
There is no standard implementation of getline which does not require a stream.
That said you can use ch to seed a istringstream to count the words in the string, but basic_istream<CharT, Traits>& getline(basic_istream<CharT, Traits>&& input, basic_string<CharT, Traits, Allocator>& str) assumes a newline as the delimiter so that's not what you're going to want to count words. Similarly, a getline that takes a delimiter will only break on a specific character. Instead you could use basic_istream& basic_istream::operator>> which will split words on all whitespace characters:
istringstream foo(ch);
for(auto i = 1; foo >> w; ++i) {
cout << i << ": " << w << endl;
}
Live Example
Just as a note here, defining char w[20] is just begging for an out of bounds write. At a minimum you need to define that such that if ch is filled with non-whitespace characters, w can contain it all. You could do that by defining char w[100].
But if someone were to come and increase the size of ch without changing the size of w and then you'd be in trouble again. In C++17 you could define w like this char w[size(ch)] prior to that you could do char w[sizeof(ch) / sizeof(ch[0])]
But your best option is probably to just make both w and ch strings so they can dynamically resize to accommodate user input.

How does char extraction differ from string extraction?

When disabling whitespace skipping with chars and strings the behavior is different. It seems the only way to extract an entire string (including whitespace characters) is to use chars and noskipws. But this is not possible with strings because it won't extract after the first space.
std::string test = "a b c";
char c;
std::istringstream iss(test);
iss.unsetf(std::ios_base::skipws);
while (iss >> c)
std::cout << c;
will output a b c but change c to string and it only outputs a.
The >> operator for a string extracts words, and stops at the
first white space it sees. If it doesn't skip initial white
space, then it stops immediately, and returns an empty string.
You don't say how you want the string to be delimited. To read
until the end of line, just use std::getline. To read until
the end of file, you can use something like:
std::istringstream collector;
collector << iss.rdbuf();
std::string results = collector.str();
It's not the most efficient, but if the file is small, it will
do.

Reading till the end of a line in C++

I have a text file like this :
Sting Another string 0 12 0 5 3 8
Sting Another string 8 13 2 0 6 11
And I want to count how many numbers are there. I think my best bet is to use while type cycle with a condition to end counting then another line starts but I do not know how to stop reading at the end of a line.
Thanks for your help in advance ;)
Split your input stream into lines
std::string line;
while (std::getline(input, line))
{
// process each line here
}
To split a line into words, use a stringstream:
std::istringstream linestream(line); // #include <sstream>
std::string word;
while (linestream >> word)
{
// process word
}
You can repeat this for each word to decide whether it contains a number. Since you didn't specify whether your numbers are integer or non-integers, I assume int:
std::istringstream wordstream(word);
int number;
if (wordstream >> number)
{
// process the number (count, store or whatever)
}
Disclaimer: This approach is not perfect. It will detect "numbers" at the beginning of words like 123abc, it will also allow an input format like string 123 string. Also this approach is not very efficient.
Why don't you use a getline()?
End of Line is represented by '\n' character.
Put a condition in your while loop to end when it encounters '\n'

Getting Stringstream to read from character A to B in a String

Is there some way to get StringStream to read characters A through B of a string?
For example, something like (but not):
stringstream mystringstream;
mystringstream.read(char* s, streamsize n, **int firstcharacter**);
Thanks for your help.
EDIT: By A through B I mean, for example, the third through fifth characters.
EDIT: Example: get characters three through five of "abcdefghijklmnop" would give "cde".
or, if you need a substring in position A through B, you can do
string s = mystring.substr(A, B-A+1); // the second parameter is the length
if this must be a stringstream, you can do
string s = mystringstream.str().substr(A, B-A+1);
You can use the substr-method:
std::string foo = "asdfersdfwerg";
std::cout << foo.substr(5, 4) << std::endl;
This will print rsdf.