I was trying to build a vector of strings.
Some of the strings also contain Spaces.
That's why I was using getline(cin,string_name).
My code looks like
for(int i=0;i<n;++i)
{
getline(cin, s);
vec.push_back(s);
}
When I was taking input
ADAM BOB JOHNSON
It stopped after taking two input words, and the vector contents displayed are
(HERE SPACE IS DISPLAYED)ADAM BOB
What does it mean.Is it taking NULL string as input for the first string ?
It will be really helpful if someone tells me how to take the strings and display it.Thanks.
Abhijit,
Your information is, obviously, not enough. Assuming that your code is written on C++, I made this test cpp:
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> vec;
std::string s;
int n = 1;
for(int i = 0; i < n; ++i)
{
getline(std::cin, s);
vec.push_back(s);
std::cout << vec.at(i) << std::endl;
}
return 0;
}
Compiled with g++ and fed it with "ADAM BOB JOHNSON" string on input. Everything worked as it planned and it output was exact same as input. So I can see no error in here.
Sorry, cannot make it a comment due to insufficient reputation so far.
UPD: Found the issue. getline first gets '\n', we left after '3' (which is needed for std::cin >> n;) hence, you just need to ignore one string. The code:
#include <iostream>
#include <vector>
#include <string>
int main()
{
int n;
std::cin >> n;
std::vector<std::string> vec;
std::string s;
std::getline(std::cin, s);
for(int i = 0; i < n; ++i)
{
std::getline(std::cin, s);
vec.push_back(s);
// std::cout << vec.at(i) << std::endl;
}
for(int i=0;i<n;++i){
std::cout << vec[i] <<" " << std::endl;
}
return 0;
}
works fine for me.
And yep, #pmaxim98 made it first, sorry, was editing the reply and haven't seen your comment.
Related
So guys, Actually What I wanna do here is that when I input 3,12,36 the output will be:
3
12
36
But here I have difficulty on how to make it output all the answer. What I have been doing is that when you input 3,12,36 it will output 3 12 only and if you type 3,12,36,48 it will output 3 12 36.
So it will always miss the last integer because my while loop is not correct I guess. but if I change it into
while(output >> life|| output >> ch)
It doesn't work either. I've done a lot of research but it still makes me confused and I'm still stuck on this part.
vector<int> parseInts(string str) {//23,4,56
vector<int>lifeishard;
stringstream output;
string lifeisgood = str;
output.str(lifeisgood);
int life;
char ch;
while(output >> life >> ch){
lifeishard.push_back(life);
//lifeishard.push_back(life2);
//lifeishard.push_back(life3);
}
return lifeishard;
}
int main() {
string str;
cin >> str;
vector<int> integers = parseInts(str);
for(int i = 0; i < integers.size(); i++) {
cout << integers[i] << "\n";
}
return 0;
}
On your last number, the while loop fails because there's no character at the end. Just the end of the string. So it doesn't execute the push_back inside the loop.
Change it so that the while loop just gets the number. Then do the push_back in the loop. Then in the loop, after the push, get the comma character. Don't bother checking for failure getting the comma because when it goes around the while loop again it will fail and exit.
I changed to using getline in your main. I changed your loop index to size_t because it is never a good idea to mix signed and unsigned integers, and whenever you use a size() function, it's a size_t. When posting your program it really should include everything. My fixed up version of your program:
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
vector<int> parseInts(string str) {//23,4,56
vector<int>lifeishard;
stringstream output;
string lifeisgood = str;
output.str(lifeisgood);
int life;
char ch;
while(output >> life){
lifeishard.push_back(life);
output >> ch;
}
return lifeishard;
}
int main() {
string str;
getline(cin, str);
vector<int> integers = parseInts(str);
for(size_t i = 0; i < integers.size(); i++) {
cout << integers[i] << "\n";
}
// Here is how we do for loops over containers in modern C++
for(auto x: integers) {
cout << x << '\n';
}
return 0;
}
A combination of stringstream, getline with delimiter and stoi would be enough for the conversion:
From the C++ reference for getline with delimiter:
Extracts characters from is and stores them into str until the delimitation character delim is found.
With this in mind, the code example below assumes the input is well-formed:
Example
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
vector<int> parseInts(const string& str, const char delim = ',')
{
vector<int> parsed;
stringstream ss(str);
string s;
while (getline(ss, s, delim)) // <- stores input in s upon hitting delimiter
parsed.push_back(stoi(s)); // <-- convert string to int and add it to parsed
return parsed;
}
int main()
{
string str = "3,12,36"; // <-- change to cin if you'd like
vector<int> ints = parseInts(str);
for (auto& i : ints)
cout << i << "\n";
}
Output
3
12
36
See more: getline, stoi
using namespace std;
int main()
{
string dna1;
getline(cin, dna1);
string dna2;
getline(cin, dna2);
int hammingDistance=0;
for (int i=0; i < dna1.length(); ++i) {
if (dna1[i] !=dna2[i]) {
hammingDistance++;
}
}
cout <<"HammingDistance is: " << hammingDistance << '\n’;
}
So this is the code I have compiled but it seems to have some error this is from the website Rosalind to which I have added the link below:http://rosalind.info/problems/hamm/
As Michael Roy commented, you're missing the header files you need, iostream and string.
#include <iostream>
#include <string>
You need to format your code though. As it is, it's hard to read, in a regular production-size project, it would be impossible. I also don't recommend using the "using namespace std;" declaration. It's a bad beginner habit to get into.
Everyone has their own specific preferences, but this is roughly what your code should look like.
#include <iostream>
#include <string>
int main()
{
std::string dna1;
std::cin >> dna1;
//getline(cin, dna1);
std::string dna2;
std::cin >> dna2;
//getline(cin, dna2);
int hammingDistance = 0;
for (int i=0; i < dna1.length(); ++i) {
if (dna1[i] != dna2[i]) {
hammingDistance++;
}
}
std::cout <<"HammingDistance is: " << hammingDistance << '\n';
return 0;
}
I used the standard stream methods for input for consistency, but there's nothing technically wrong with other methods, as long as you don't use gets().
I need some help debugging my code. This code is intended to reverse the words in a string that is in the form of a sentence [assuming that the string does not have a "." at the end]. For some reason what I'm getting as an output is the indented output plus an extra space after the first word as well as the indented output minus the first word. I am a beginner at coding; so if possible, I would appreciate more simple to understand solutions, or a solution that uses a loop, strings, and arrays.
Sample Input:
My name is Edward
Intended Output:
Edward is name My
Output Received:
Edward is name
Here is my code so far:
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main() {
string s, n, a;
getline(cin, s);
for (int i = s.length(); i >= 0; i--){
if (s[i] != 32 ) {
n += s[i];
}
else {
for (int j = n.length() -1; j >= 0; j--){
a += n[j];
}
cout << a << ' ';
n.clear();
a.clear();
}
}
cin.ignore();
getchar();
return 0;
}
Also, I just noticed that there is also an extra space at the end. If there is a way to maybe cancel outputting the last space; please tell me.
Thanks for reading, I appreciate your help.
As mentioned in my comment, you're reversing the whole string by characters, but you need to split up for words and reverse:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
string s, n;
getline(cin, s);
std::istringstream iss(s);
std::vector<string> words;
while(iss >> n) {
words.push_back(n);
}
std::reverse(words.begin(),words.end());
for(auto word : words) {
std::cout << word << ' ';
}
getchar();
return 0;
}
Live Demo
So this is really just an additional step of abstraction from πάντα ῥεῖ's excellent answer. You can use istream_iterator and ostream_iterator to further simplify your code.
The entire code to answer your question can be boiled down to:
const vector<string> words{ istream_iterator<string>(cin), istream_iterator<string>() };
copy(crbegin(words), crend(words), ostream_iterator<string>(cout, " "));
Live Example
Edit: Thanks for the help from the comments and answers, I fixed the problem with the extra space and added something at the end that outputs the final word. It's not perfect, but it works. :)
#include <iostream>
#include <string>
using namespace std;
int main() {
string s, n;
getline(cin, s);
for (int i = s.length() -1; i >= 0; i--){
if (s[i] != 32) {
n += s[i];
}
else {
for (int j = n.length() -1; j >= 0; j--){
cout << n[j];
}
cout << ' ';
n.clear();
}
}
for (int k = n.length() -1 ; k >= 0; k--)
cout << n[k];
cin.get();
return 0;
}
you can use strrev(); function instead all of your for block.
I'm trying to make a program that flips the words you input. The problem comes when I try to write the word and it asks twice for the input:
cin >> Arr >> myStr;
It is logical that it ask twice but everytime I try to use getline the compiler gives out an error (and even if it worked I have to give the input twice) and I need it to include spaces in the character array.
Here is my full code:
#include <iostream>
#include <string>
using namespace std;
string myStr;
string newVal;
int i;
int main()
{
char Arr[i];
cout << "Enter: ";
cin >> Arr >> myStr;
for (i = myStr.length(); i >= 0; i--)
{
cout << Arr[i];
}
cout << endl;
return 0;
}
The loop works.
The first problem can be corrected by achieving the proper use of getline.
The second one, I have got no idea (use a single input to assign two variables).
Thanks in advance, and I apologise if this is too much of a ridiculous question.
Maybe you can try to have a look to this solution that it's more C++ style than yours:
#include <iostream>
#include <string>
int main() {
std::string myStr;
std::cout << "Please give me a string: ";
if(std::getline(std::cin, myStr)) {
for(std::string::reverse_iterator it = myStr.rbegin();
it != myStr.rend();
++it) {
std::cout << *it;
}
std::cout << std::endl;
}
}
I suggest to you to use always std::string in C++ because has all the methods and function that you could need. So don't waste your time with char array like you do in C.
Here it is, as I said. I was digging around and came up with this:
#include <iostream>
#include <string>
using namespace std;
string myStr;
int i;
int main()
{
cout << "Enter: ";
getline (cin, myStr);
i = myStr.size();
cout << i << endl;
char Arr[i];
for (int a = 0; a <= i; a++)
{
Arr[a] = myStr[a];
}
for (i; i >= 0; i--)
{
cout << Arr[i];
}
return 0;
}
I did not know string contents could also have array-like behaviour. Test it out! Works like a charm (as far as tested).
The way I formatted the code it takes no more than 27 lines of code.
Thanks everyone involved, you helped me a lot.
P.S: Couldn't answer before, I can't do it soon enough with my reputation.
The below code is not reading the correct chars from the file. Any idea what is wrong?
ifstream inFile;
inFile.open("chars.txt");
char ch; //dummy variable
char first, last;
int first1, last1;
for(int i=0;i<SIZE;i++)
{
for(int j=0;j<5;j++){
inFile.get(first);
inFile.get(last);
at this point first and last are not the correct chars from the file. (on the first run through the loop) It is probably something simple, but I am really bad at this.
Thanks in advance.
You don't need to parse the numbers manually like that.
Instead of using the get function, I'd recommend using the extraction operator >>, like in the following example:
#include <vector>
#include <fstream>
#include <iostream>
int main()
{
std::vector<int> values;
std::ifstream inFile("chars.txt");
int temp;
// Read the values in one at a time:
while (inFile >> temp)
{
values.push_back(temp);
}
// Demonstrate that we got them all by printing them back out:
for (unsigned int i = 0; i < values.size(); ++i)
{
std::cout << "[" << i << "]: " << values[i] << std::endl;
}
}
I am not sure if this applies to C++, but I had this problem in C#.
I had to use Char.GetNumericValue(); on the character being read.
Sample code in C#:
int myInt;
char myChar = '5';
myInt = Char.GetNumericValue(myChar);
Console.WriteLine("My character as int: "+myInt.ToString());