If I have input like this,
apple+banana=3
And I want to store apple in one string and banana in another string and 3 in an integer, how can I do it? How can I skip those + and = signs? Thanks!
std::getline takes an optional delimiter as a third argument, so you could do something like:
#include <iostream>
#include <string>
int main() {
std::string a, b;
int c;
std::getline(std::cin, a, '+');
std::getline(std::cin, b, '=');
std::cin >> c;
}
Related
I'm using the following code:
string a, b, c;
cin >> a >> b >> c;
Explained: if a user inputs e.g. "hello new world hi"
then the mapping is a='hello', b='new' and c='world'. The "hi" will be ignored - and that's the problem!
What i want is, that in case of a wrong number of arguments (more or less than 3), the user should be forced to input again (maybe by an error message).
In your code, if you type in 4 words then the last word will exist somewhere on your machine(maybe on keyboard buffer). Thus, if you use cin to type value for another variable, the last word will be assign to the variable. So to check if user has typed error or not, you can do as following:
#include<iostream>
#include<string>
#include <sstream>
using namespace std;
int main()
{
string a, b, c;
cin >> a >> b >> c;
string check="";
getline(cin, check);
if (check != "")
{
cout << "input error,try again!";
}
return 0;
}
Use getline(cin, stringName)
After the input iterate through string check the index of spaces, and then split it into whatever you want.
You even don't need to declare three string to store. You can use std::getline.
std::string a;//,b,c;
std::getline(std::cin,a); //<< b << c;
std::cout <<a;
You can read whole line with std::getline, and then separate line by spaces. For example:
#include <string>
#include <vector>
#include <iostream>
// some code...
std::string text;
std::getline(std::cin, text);
std::vector<std::string> words;
int wordCount = 0;
while (auto space = text.find_first_of(' '))
{
wordCount++;
if (wordCount > 3)
{
std::cout << "Max 3 words!" << std::endl;
break;
}
words.push_back(text.substr(0, space));
text = text.substr(space + 1);
}
This way you will have max 3 words in vector words, you can get them by calling words[0] for first, etc. At 4th read word error is printed and while loop stops.
I have a file.txt such as :
15 25 32 // exactly 3 integers in the first line.
string1
string2
string3
*
*
*
*
What I want to do is, reading 15,25,32 and store them into lets say int a,b,c;
Is there anyone to help me ? Thanks in advance.
The standard idiom uses iostreams:
#include <fstream>
#include <sstream>
#include <string>
std::ifstream infile("thefile.txt");
std::string first_line;
if (!infile || !std::getline(first_line, infile)) { /* bad file, die */ }
std::istringstream iss(first_line);
int a, b, c;
if (!(iss >> a >> b >> c >> std::ws) || iss.get() != EOF)
{
// bad first line, die
}
// use a, b, c
You can use a std::ifstream to read file content:
#include <fstream>
std::ifstream infile("filename.txt");
Then you can read the line with the numbers using std::getline():
#include <sstream>
#include <string>
std::string line;
std::getline(infile, line);
Then, you can use a std::istringstream to parse the integers stored in that line:
std::istringstream iss(line);
int a;
int b;
int c;
iss >> a >> b >> c;
I am asking the user to input a string on console. But I don't know the length of string.
How can I define a structure to fit the input with variable length?
int main(){
int i;
char s[10];
cout << "input string:";
cin >> s;
return 0;
}
The sample code will cause heap corruption if the input string length exceeds 10.
Use std::string instead. For example:
#include <string>
std::string s;
std::cout << "input string:";
std::cin >> s;
Or use std::getline to get a line until endline character
std::getline(std::cin, s);
In c++, you should use std::string instead of char[], especially for variable length strings.
This is a working, general example that allows you to read in strings including white space:
#include <string>
#include <iostream>
int main()
{
std::string s;
std::cout << "Type a string\n";
std::getline(std::cin, s);
std::cout << "You just typed \"" << s << "\"\n";
}
cplusplus.com says that the >> operator for strings from an input stream uses whitespaces as a seperator. so if you need your string to be able to contain whitespaces you have to use std::getline(...) (wich is different from istream::getline(...)!!!!)
basically it goes like this:
std::string inputString;
std::getline(cin, inputString);
my answer was inspired by this answer
#include <iostream>
#include <string>
using namespace std;
int main(){
int i;
string s;
cout << "input string:";
cin >> s;
return 0;
}
Use std::string instead of char[].
If you need to use char[] after the input, you can refer to these questions:
std::string to char*
convert string to char*
For example,
string s1;
cin >> s1;
char *s2;
s2 = new char[s1.length() + 1]; // Including \0
strcpy(s2, s1.c_str());
delete []s2;
You can use malloc and free if you don't know about new and delete.
Basically it is suggested that you should always std::string to get variable length input. Still if you need to store the input in an array to pass it to a function or something. you can go for this. Though its quite lame.
/* #include <string> */
std::string s;
std::cout<<"Enter the String";
std::getline(std::cin, s);
char *a=new char[s.size()+1];
a[s.size()]=0;
memcpy(a,s.c_str(),s.size());
std::cout<<a;
Regards
Genocide_Hoax
Suppose I want to read line a of integers from input like this:
1 2 3 4 5\n
I want cin to stop at '\n' character but cin doesn't seem to recognize it.
Below is what I used.
vector<int> getclause() {
char c;
vector<int> cl;
while ( cin >> c && c!='\n') {
cl.push_back(c);
cin>>c;
}
return cl;
}
How should I modify this so that cin stop when it see the '\n' character?
Use getline and istringstream:
#include <sstream>
/*....*/
vector<int> getclause() {
char c;
vector<int> cl;
std::string line;
std::getline(cin, line);
std::istringstream iss(line);
while ( iss >> c) {
cl.push_back(c);
}
return cl;
}
You can read all whitespace by setting noskipws on the istream:
#include <ios>
#include <iostream>
#include <vector>
using std::vector;
vector<int> getc() {
char c;
vector<int> cl;
std::cin >> std::noskipws;
while (std::cin >> c && c != '\n') {
cl.push_back(c);
std::cin >> c;
}
return cl;
}
If the standard input contains only a single line, you might as well construct the vector with the istream_iterator:
#include <iostream>
#include <iterator>
#include <vector>
using std::vector;
vector<int> getc() {
// Replace char with int if you want to parse numbers instead of character codes
vector<int> cl{
std::istream_iterator<char>(std::cin),
std::istream_iterator<char>()
};
return cl;
}
You can use the getline method to first get the line, then use istringstream to get formatted input from the line.
Use std::getline, this will do the trick
getchar() is more efficient than cin when working with characters at this situation
I tried to do the same with a line of characters with unknown length and want it to stop at a newline but it has an infinite loop and haven't detect the newline, so I just used getchar() instead of cin and it works
From this link, it is quite simple to achieve this.
#include <stdio.h>
int main(void) {
int i=0,size,arr[10000];
char temp;
do{
scanf("%d%c", &arr[i], &temp);
i++;
} while(temp!= '\n');
size=i;
for(i=0;i<size;i++){
printf("%d ",arr[i]);
}
return 0;
}
This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
C++ alternative to sscanf()
I have the following line of code
sscanf(s, "%*s%d", &d);
How would I do this using istringstream?
I tried this:
istringstream stream(s);
(stream >> d);
But it is not correct because of *s in sscanf().
The %*s used with sscanf basically means to ignore a string (any characters up until a whitespace), and then after that you're telling it to read in an integer (%*s%d). The asterisk (*) has nothing to do with pointers in this case.
So using stringstreams, just emulate the same behaviour; read in a string that you can ignore before you read in the integer.
int d;
string dummy;
istringstream stream(s);
stream >> dummy >> d;
ie. With the following small program:
#include <iostream>
#include <sstream>
using namespace std;
int main(void)
{
string s = "abc 123";
int d;
string dummy;
istringstream stream(s);
stream >> dummy >> d;
cout << "The value of d is: " << d << ", and we ignored: " << dummy << endl;
return 0;
}
the output will be: The value of d is: 123, and we ignored: abc.
There is no pointer manipulation in your code.
As AusCBloke has said, you need to read the all of the unwanted characters before the int into a std::string. You also want to ensure that you handle malformed values of s, such as those with any integers.
#include <cassert>
#include <cstdio>
#include <sstream>
int main()
{
char s[] = "Answer: 42. Some other stuff.";
int d = 0;
sscanf(s, "%*s%d", &d);
assert(42 == d);
d = 0;
std::istringstream iss(s);
std::string dummy;
if (iss >> dummy >> d)
{
assert(dummy == "Answer:");
assert(42 == d);
}
else
{
assert(!"An error occurred and will be handled here");
}
}