I new to programming and was trying to implement struct program in c++, it's simple program but it's not printing proper result. please tell me why?
#include <iostream>
using namespace std;
struct classroom {
int number;
char name[9];
int marks;
void getAndPrint()
{
cout << "struct classroom ";
cin >> number;
cout << number << '\n';
cin.get(name, 9);
//cin>>name;
cout << name;
cin >> marks;
cout << marks;
}
};
int main()
{
classroom room1;
room1.getAndPrint();
int i;
cin >> i;
return 0;
}
In function getAndPrint() I'm using cin.get()..the compiler execute the properly till printing the "number" but when it comes on cin.get(name,9) it print garbage and skips the rest of the code inside the funcion. If i use cin>>name then it's working properly.
Can anyone tell what exactly is the problem?
first, in C++, struct is class with access_modifier is public.
second, you should try read:
Difference between cin and cin.get() for char array
The structure definition does not contain such a function like see
room1.see();
^^^^
I think you mean
room1.getAndPrint();
Also before this statement
cin.get(name, 9);
insert at least this statement
cin.ignore();
Or you even can include the header <limits> and insert statement
#include <limits>
//...
cin.ignore( std::numeric_limits<streamsize>::max(), '\n' );
Related
This question already has answers here:
How do I pass a cin'd c style string to a function?
(2 answers)
Closed last year.
Here is my code I am expecting the output but I am not getting .It stop after taking the input
I am expecting the output if i give name Harsh
Your name is Harsh
#include <iostream>
#include <cstring>
using namespace std;
int main() {
cout << "Enter your name" << endl;
char *s;
cin >> s;
cout << "Your name is " << s;
return 0;
}
I have also tried with cin.getline(s,100);but still it is not working.
So I request to you to solve the problem and give me solution.
Your code has undefined behavior because you are not allocating any memory for s to point at. s is an uninitialized pointer.
Try this instead:
#include <iostream>
using namespace std;
int main(){
cout << "Enter your name" << endl;
char s[100];
cin >> s; // or: cin.getline(s,100);
cout << "Your name is " << s;
return 0;
}
Alternatively, you should use std::string instead, eg:
#include <iostream>
#include <string>
using namespace std;
int main(){
cout << "Enter your name" << endl;
string s;
cin >> s; // or: getline(cin,s);
cout << "Your name is " << s;
return 0;
}
s in your code is unallocated.
Since it is C++ we're talking about, you probably don't want to use pointers and memory allocation, and use std::string instead.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
cout << "Enter your name" << endl;
string s; // Instead of dealing with char* allocation and memory issues.
cin >> s;
cout << "Your name is " << s;
return 0;
}
you have done it correctly but the problem with output is because of the memory allocation.
You have to allocate memory and try to avoid the concept of a pointer in that. Instead
Use string s;
or
char s[50];
When I am trying to store more than one word in a string variable, it only outputs one word when I tell the program to print it. This is an example:
#include <iostream>
using namespace std;
string i;
int main() {
cout << "Input more than one word." << endl;
//in this case the user will input whats up//
cin >> i;
cout << i << endl;
//the program outputs 'whats'//
}
Instead of using cin >> i, use getline(cin, i).
The difference is that, with getline() you get all the words in a line, whereas with operator>> you get only one word at a time.
Replace that:
cin >> i;
for:
getline(cin, i);
and it will work :)
I've read that getchar() should actually be preferred over _getch() ( _getch() also needs including conio.h ). However, if I use getchar() in this sample program...
#include <iostream>
#include <conio.h>
using namespace std;
class student {
int id;
int marks;
public:
void getdata() {
cout << "\n Enter id";
cin >> id;
cout << "\n Enter marks";
cin >> marks;
}
void putdata() {
cout << "\n" << id << "\t" << marks;
}
};
int main() {
student tom;
tom.getdata();
tom.putdata();
getchar(); // vs. _getch();
return 0;
}
..then using getchar() won't wait for the input of a character to prevent the console window from being closed too early, which _getch() does.
Does anyone know the reason for this? And should getchar() really be preferred over _getch()?
BTW, I'm using MS Visual Studio 2015.
Thanks in advance and kind regards
EDIT: I'd consider my question as not being a duplicate actually, since I was wondering about the reason for the different behavior, which had not been answered under "Is there a decent wait function in C++?", and which got clarified now.
#include <string>
std::string input;
std::cin >> input;
The user wants to enter "Hello World". But cin fails at the space between the two words. How can I make cin take in the whole of Hello World?
I'm actually doing this with structs and cin.getline doesn't seem to work. Here's my code:
struct cd
{
std::string CDTitle[50];
std::string Artist[50];
int number_of_songs[50];
};
std::cin.getline(library.number_of_songs[libNumber], 250);
This yields an error. Any ideas?
It doesn't "fail"; it just stops reading. It sees a lexical token as a "string".
Use std::getline:
#include <string>
#include <iostream>
int main()
{
std::string name, title;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
std::cout << "Enter your favourite movie: ";
std::getline(std::cin, title);
std::cout << name << "'s favourite movie is " << title;
}
Note that this is not the same as std::istream::getline, which works with C-style char buffers rather than std::strings.
Update
Your edited question bears little resemblance to the original.
You were trying to getline into an int, not a string or character buffer. The formatting operations of streams only work with operator<< and operator>>. Either use one of them (and tweak accordingly for multi-word input), or use getline and lexically convert to int after-the-fact.
You have to use cin.getline():
char input[100];
cin.getline(input,sizeof(input));
The Standard Library provides an input function called ws, which consumes whitespace from an input stream. You can use it like this:
std::string s;
std::getline(std::cin >> std::ws, s);
Use :
getline(cin, input);
the function can be found in
#include <string>
You want to use the .getline function in cin.
#include <iostream>
using namespace std;
int main () {
char name[256], title[256];
cout << "Enter your name: ";
cin.getline (name,256);
cout << "Enter your favourite movie: ";
cin.getline (title,256);
cout << name << "'s favourite movie is " << title;
return 0;
}
Took the example from here. Check it out for more info and examples.
How do I read a string from input?
You can read a single, whitespace terminated word with std::cin like this:
#include<iostream>
#include<string>
using namespace std;
int main()
{
cout << "Please enter a word:\n";
string s;
cin>>s;
cout << "You entered " << s << '\n';
}
Note that there is no explicit memory management and no fixed-sized buffer that you could possibly overflow.
If you really need a whole line (and not just a single word) you can do this:
#include<iostream>
#include<string>
using namespace std;
int main()
{
cout << "Please enter a line:\n";
string s;
getline(cin,s);
cout << "You entered " << s << '\n';
}
THE C WAY
You can use gets function found in cstdio(stdio.h in c):
#include<cstdio>
int main(){
char name[256];
gets(name); // for input
puts(name);// for printing
}
THE C++ WAY
gets is removed in c++11.
[Recommended]:You can use getline(cin,name) which is in string.h
or cin.getline(name,256) which is in iostream itself.
#include<iostream>
#include<string>
using namespace std;
int main(){
char name1[256];
string name2;
cin.getline(name1,256); // for input
getline(cin,name2); // for input
cout<<name1<<"\n"<<name2;// for printing
}
I rather use the following method to get the input:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string name;
cout << "Hello, Input your name please: ";
getline(cin, name);
return 0;
}
It's actually super easy to use rather than defining the total length of array for a string which contains a space character.
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.