Using cin.getline with string declared - c++

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line,line2;
char dude[20];
cin.getline(dude,20);
fstream myfile ("example.txt",ios::in);
if(!myfile)
{
cout<<"Not Found! ";
system("pause");
}
while (!myfile.eof())
{
getline(myfile,line);
cout<<line;
}
myfile.close();
exit(0);
}
This works but if i do this:
int main () {
string line,line2,dude;
It gives me an error.
[Error] no matching function for call to 'std::basic_istream::getline(std::string&, int)'
WHY?

std::cin.getline() expects a char* buffer (docs)
std::getline() expects a std::string buffer (docs)
When you change the type, you have to change which function you call, too.

char buf[20] is not a string, it is a character array. If you terminate the array with a '\0' byte, then it can be said to be a c-string. Still not a std::string, though.
The function cin.getline() expects two parameters: a pointer to an array of characters and a count of how many characters the buffer supports - it then populates it with a c-string from cin.
There is no variant of cin.getline() which supports a std::string. For that, you need to use std::getline(iostream, string), e.g.
std::string line;
std::getline(std::cin, line);

Related

How to pass string to gets_s() in C++?

#include<iostream>
using namespace std;
int main() {
string str;
gets_s(str);
cout << str << endl;
return 0;
}
When I tried to run the above code it threw an error that no instance of gets_s() matched the argument list.
How can I pass an std::string instead of a char[] to gets_s() function if is possible?
The C function get_s takes a char* and a length argument, not a std::string.
Your best options are:
Formatted input:
std::cin >> str;
Read a line:
std::getline(std::cin, str);
Don't do that. Use the stream in a normal way:
#include<iostream>
using namespace std;
int main()
{
string str;
cin >> str;
cout << str << endl;
return 0;
}
gets_s has a significant limitation in that you must provide an upper limit on the number of characters you want to read.
Since you are using string the superior alternative is to use getline
#include <iostream>
#include <string>
using namespace std;
string str;
getline(cin, str);
This will expand the string to hold as many characters as are entered by the user.
gets_s() takes two arguments: pointer to char array and maximal size (your call is missing it). You cannot pass std::string - only C style strings.
Instead of C functions, why not use C++ way std::cin >> str or getline(std::cin, str)?
In C also don't use gets_s() (it's optional in C11) or gets() - use fgets() instead.
Well, there are a lot of answers about std::getline, but in case if you really need to use get_s, you may write such code:
size_t length = 10; // Just for example
std::string my_string(length, 0);
get_s(&my_string[0], length); // C++14 and older
get_s(my_string.data(), length); // C++17 and newer

C++ 'getline' No instance of overloaded function matches argument list

Trying to use getline but the error keeps saying:
No instance of overloaded function matches argument list.
#include <iomanip>
#include <string>
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
int lengthInput;
int widthInput;
ifstream fileOpening;
fileOpening.open("testFile.txt");
while (!fileOpening.eof())
{
//ERROR ON NEXT TWO LINES OF CODE**
getline(fileOpening, lengthInput, ' ');
getline(fileOpening, widthInput, ' ');
}
system("pause");
return 0;
The 2nd parameter of std::getline() expects a std::string to write to, but in both cases you are passing in an int instead. That is why you are getting the error - there really is no version of std::getline() that matches your code.
The second argument of getline is expected to be a reference to a std::string, not a reference to an int.
If you expect that the pair of values can be read from multiple lines, you can use:
while (fileOpening >> lengthInput >> widthInput)
{
// Got the input. Use them.
}
If you expect that the pair of values must be read from each line, you'll have to use a different strategy.
Read lines of text.
Process each line.
std::string line;
while ( fileOpening >> line )
{
std::istringstream str(line);
if (str >> lengthInput >> widthInput)
{
// Got the input. Use them.
}
}
Important Note
Don't use
while (!fileOpening.eof()) { ... }
See Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?.

How can I take a string input like this?

If I have a string containing unknown number of words, and I have to scan it in multiple strings in C++. How can I do it?
For eg:
"I am a boy". I want, each of these individual words to be in a string.
"My name is John Lui". Each of these as well.
One way that I could think of was to use, getline in c++ and then parse through the entire string until a character is found and store in seperate strings. I want to know is there a better method? Thanks!
Also, I want to know, that when using a delimiter in getline command, getline basically scans the input strings till the point delimiter is not found and puts that part of a string into a new string. However, I want to know, if the delimiter is not present at all, then what happens? Does it throw an exception or it takes input the whole string till the newline character? Thanks!
However you could use std::getline
Which uses a string instead of a char array. It's easier to use string
since they know their sizes, they auto grow etc. and you don't have to
worry about the null terminating character and so on. Also it is
possible to convert a char array to a string by using the appropriate
string contructor.
You can do it by stringstream:
// stringstream::str
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream, std::stringbuf
using namespace std;
int main ()
{
std::string str;
getline( std::cin, str );
std::stringstream ss;
ss<<str;
std::string s;
while(ss>>s)
{
std::cout << s << '\n';
}
return 0;
}
Input: I am a boy
Output:
I
am
a
boy
If you think that, you want each word to store in a vector, you can do it like:
// stringstream::str
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream, std::stringbuf
#include <vector>
using namespace std;
int main ()
{
vector <string> V;
V.clear();
std::string str;
getline( std::cin, str );
std::stringstream ss;
ss<<str;
std::string s,s1;
while(ss>>s)
{
V.push_back(s);
}
return 0;
}

Beginner Error with "getline"

this is my first time posting a question so I hope I'm getting this right. Anyways, I'm trying to create a program to ask the user for a string, count the types and numbers of letters, then output the frequency of the letters. So far I'm having an error with even getting the right input, and just can't figure out what the issue is. My (relevant) code is:
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;
string getPhrase(const string & phrase); //Function for gathering string input
int main()
{
const string phrase;
getPhrase(phrase);
...
}
string getPhrase(const string &phrase)
{
cout<<"Enter phrase: "
getline(cin, phrase);
return (phrase);
}
When I run, this I get the error:
freq.cpp: In function ‘std::string getPhrase(const std::string&)’:
freq.cpp:21: error: no matching function for call to ‘getline(std::istream&, const
std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)’
I have no idea what I'm doing wrong, and just can't seem to find anything online that's relevant to what I'm doing.
Your getPhrase should look like this:
std::string getPhrase()
{
std::string result;
std::cout << "Enter phrase: ";
std::getline(std::cin, result);
return result;
}
Then:
int main()
{
std::string phrase = getPhrase();
// ...
}
const string phrase;
remove const in function parameter and local variable declaration since otherwise you can't accept user input to a const variable, which means nonchangable/ non-modifiable.
Like the following:
string getPhrase(string & phrase); //Function for gathering string input
int main()
{
string phrase;
getPhrase(phrase);
//...
}
Notice that phrase is a const string. That means it's constant and can't be modified. Therefore you can't use getline to set phrase to the user's input.
You should declare phrase with string phrase; and then make the parameter of getPhrase a non-const reference.
string getPhrase(string& phrase); //Function for gathering string input
int main()
{
string phrase;
getPhrase(phrase);
...
}

How to read and write a STL C++ string?

#include<string>
...
string in;
//How do I store a string from stdin to in?
//
//gets(in) - 16 cannot convert `std::string' to `char*' for argument `1' to
//char* gets (char*)'
//
//scanf("%s",in) also gives some weird error
Similarly, how do I write out in to stdout or to a file??
You are trying to mix C style I/O with C++ types. When using C++ you should use the std::cin and std::cout streams for console input and output.
#include <string>
#include <iostream>
...
std::string in;
std::string out("hello world");
std::cin >> in;
std::cout << out;
But when reading a string std::cin stops reading as soon as it encounters a space or new line. You may want to use std::getline to get a entire line of input from the console.
std::getline(std::cin, in);
You use the same methods with a file (when dealing with non binary data).
std::ofstream ofs("myfile.txt");
ofs << myString;
There are many way to read text from stdin into a std::string. The thing about std::strings though is that they grow as needed, which in turn means they reallocate. Internally a std::string has a pointer to a fixed-length buffer. When the buffer is full and you request to add one or more character onto it, the std::string object will create a new, larger buffer instead of the old one and move all the text to the new buffer.
All this to say that if you know the length of text you are about to read beforehand then you can improve performance by avoiding these reallocations.
#include <iostream>
#include <string>
#include <streambuf>
using namespace std;
// ...
// if you don't know the length of string ahead of time:
string in(istreambuf_iterator<char>(cin), istreambuf_iterator<char>());
// if you do know the length of string:
in.reserve(TEXT_LENGTH);
in.assign(istreambuf_iterator<char>(cin), istreambuf_iterator<char>());
// alternatively (include <algorithm> for this):
copy(istreambuf_iterator<char>(cin), istreambuf_iterator<char>(),
back_inserter(in));
All of the above will copy all text found in stdin, untill end-of-file. If you only want a single line, use std::getline():
#include <string>
#include <iostream>
// ...
string in;
while( getline(cin, in) ) {
// ...
}
If you want a single character, use std::istream::get():
#include <iostream>
// ...
char ch;
while( cin.get(ch) ) {
// ...
}
C++ strings must be read and written using >> and << operators and other C++ equivalents. However, if you want to use scanf as in C, you can always read a string the C++ way and use sscanf with it:
std::string s;
std::getline(cin, s);
sscanf(s.c_str(), "%i%i%c", ...);
The easiest way to output a string is with:
s = "string...";
cout << s;
But printf will work too:
[fixed printf]
printf("%s", s.c_str());
The method c_str() returns a pointer to a null-terminated ASCII string, which can be used by all standard C functions.