Not getting char array as output? - c++

#include <iostream>
#include <string>
using namespace std;
int main()
{
char addi[5];
string name;
string a="ADD:";
fgets(addi,5, stdin);
cin>>name;
addi[5]='\0';
cout<<"addi"<<addi<<endl;
i have a addi char array in which i wanna store "ADD:" and name string in which i wanna store the string to be added .the input will be in format ADD:wolf .why does addi not take the "ADD:" string?? OR alternatively how would i do it since i need to compare the ADD: with some string in further steps.

My guess is that you expect the fgets call to get the first four characters, and then use std::cin to get the remaining line. However it does not work like that. The fgets call gets the complete line, even it it only writes four characters to your buffer. Then the input with std::cin will wait for input that never comes.
Instead I suggest you read the complete line with std::getline, and then split the string at the colon to get the "key" and the "value".
Actually, since std::getline supports simple tokenization, you can use two calls to read the input:
std::string op;
std::string data;
std::getline(std::cin, op, ':');
std::getline(std::cin, data);
Now the string op will contain e.g. ADD (the string before the colon), and data will contain the string after the colon.

Related

How can I write into a string like I write into a char[]

For example, if I have this function:
void read(std::string& s)
{
std::cin >> s;
}
and the input
first sentence
s will contain 'first' only.
If I would've used something like:
void read(char array[100])
{
std::cin.get(array, 100);
}
for the same input, I would've got "first sentence".
Is there any way to achieve the same effect using std::string?
This might happen (I think) because cin.get with char[] takes all the characters, even blank spaces, because it ends when it detects an end-of-line character, but cin with string stops when it encounters a space character. (just like cin>> does when being used with char[]).
So, I think that I need a cin.get() which would work for std::string.
I'm thinking about reading into a char array and then using the char* constructor of the string in order to convert the char array into a string, but I think there might be a better way to do it.
You can use std::getline().
void read(std::string& s)
{
std::getline(std::cin, s);
}
You can use getline to input the whole string std::getline(std::cin, s);
using namespace std;
void read(string& s) {
getline(cin, s);
}
Use above code for reading whole line instead of first word.

How to divide the input taken from user in two parts and assign them to two different arrays in C++?

If we take the input from user by asking them, like below:
cout << "Enter your course code and course name: ";
Now if the user enters CS201 Introduction to Programming, how can I only assign the code part, i.e. CS201 to an array, let's say;
char courseCode[10];
And how can I assign the name part in the array, let's say:
char courseName[50];
I want to do this to 5 students, using the structure defined below:
struct student
{
char courseName[50];
char courseCode[10];
};
student stu[5];
It's actually kind of simple once you remember that the input operator >> stops on white-space, and also know about the std::getline function.
Then you can do something like
std::string courseCode;
std::string courseName;
std::cin >> courseCode;
std::getline(std::cin, courseName);
Note that I use std::string for the strings instead of arrays. This is what you really should use. If you're not allowed (by your teacher or something) and must use arrays, then you can't use std::getline but instead have to use std::istream::getline instead.
Store the input in a single string say x
Now on x perform linear search for the first whitespace and split the string about the first whitespace. Store the two resultant strings in your struct.
I solved my problem using the cin.getline() functions to get the string in token pointer and then used strchr(char [], cahr) of <string> header file to separate the current string from the place where the first white space comes. Then I copied both separated strings into my desired elements of my structure using strcpy() function.

Reading an input with space in c++

currently I am doing to read input with spaces in it.
int main() {
char str[100];
string st;
cin.getline(str,100);
st=str;
}
I want to utilize the functions that come along with the string, so I am reading the input into a string. Is there any other way to read the input directly into the string which also allow space.
If you're going to use std::string objects, just use std::getline.
std::string st;
std::getline(std::cin, st);
using gets () function.
It accepts even space as input.
Eg. )
gets (variable_name);

How to provide your own delimiter for cin?

In c, I can use newline delimeter ([^\n]) with scanf. Using which I can store the line. Similarly for cin, I can use getline.
If I have to store a paragraph, I can simulate the functionality using my own special char delimiter like [^#] or [^\t] with scanf function in c.
char a[30];
scanf("%[^\#]",a);
printf("%s",a);
How to achieve the similar functionality with cin object in cpp.
istream.getline lets you specify a deliminator to use instead of the default '\n':
cin.getline (char* s, streamsize n, char delim );
or the safer and easier way is to use std::getline. With this method you don't have to worry about allocating a buffer large enough to fit your text.
string s;
getline(cin, s, '\t');
EDIT:
Just as a side note since it sounds like you are just learning c++ the proper way to read multiple deliminated lines is:
string s;
while(getline(cin, s, '\t')){
// Do something with the line
}

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.