hi!
I don't know what's the problem with this code????
I can't see the result of my third test cases about cancatenation strings with + on screen
the output is just the first string I initialized
please helping me
I'm using online compiler
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
int main()
{
int i = 4;
double d = 4.0;
string s = "i'm a";
int I;
double D;
string s1;
cin>>I;
cin>>D;
getline(cin,s1);
cout<<I+i<<endl;
D=D+d;
printf("%.1lf\n",D);
s+=s1;
cout<<s;
return 0;
}
try including <string> before iostream.
also, you getline takes what you've entered on D i guess?
i modified it a bit and on Visual Studio 2013 it works like this:
#include <string> //i already include that on habit, altough im also fairly new
//to C++
#include <iostream>
#include <iomanip>
#include <limits>
usingnamespace std;
int main()
{
int i = 4;
double d = 4.0;
string s = "i'm a";
int I;
double D;
string s1;
cout << "I" << endl;
cin >> I;
cout << "D" << endl;
cin >> D;
cout << "s1" << endl;
cin.ignore(); //seems to fix the issue ;)
getline(cin, s1);
cout << I + i << endl;
D = D + d;
printf("%.1lf\n", D);
s += s1;
cout << s;
return 0;
}
There may not be any problem in your code. What matters is that some online compilers may not produce an executable file upon success for download so that you can test and see your program results in a more informative and interactive way. Please correct me if I am wrong.
If you type the input all on a single line, for example, 2 3 fred
then the original code works - almost. (it picks up a leading space at the start of the string).
However, if the input is entered and a newline is entered after each value, then the getline doesn't work as required. That's because after entering the value for D, there is a trailing newline still in the input buffer. (there may be some other characters such as spaces if that's what the user typed). To remove those unwanted characters, after cin>>D; add the extra line,
Removing the getline() will alter the functionality. Only do that if this meets the program requirements. But don't use c-strings for this purpose, you can use a std::string with cin >> and is safer than using a c-string.
VRGaming2 wrote:
But it will always work, for sure.
It has risks, it may not work, for example if the user holds down a key and enters a very long string, it will fail, or cause unpredictable behaviour due to buffer overflow.