Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
This will crash console only if I ask the user to input pizza diameter before name.
If i ask for pizza name and then ask for pizza diameter and weight it seems to work fine - this i dont get why.
#include <iostream>
using namespace std;
struct pizza_structure
{
double diameter;
char name[100];
double weight;
};
int main()
{
pizza_structure * ps = new pizza_structure;
cout << "Enter pizza diameter: ";
cin >> ps->diameter;
cout << "Enter pizza name: ";
cin.get(ps->name, 100);
cout << "Enter pizza weight: ";
cin >> ps->weight;
cout << "Name: " << ps->name << ", diameter: " << ps->diameter << ", weight: " << ps->weight;
delete[] ps;
cin.get();
cin.get();
return 0;
}
You are mixing types of input between formatted using cin >> ... and unformatted using cin.get(...)
This goes "wrong" because the formatted input leaves the newline in the input buffer, which is then read as the first character for cin.get(...) - meaning the string is empty, and then when you read weight, it fails to read properly.
You will need to either read the extra newline with a spare cin.get() [and hope the user didn't add a some non-digit character to the input] or manually parse the input using getline and splitting the line yourself [e.g. using stringstream to read out the digits from the line].
Commercial grade UIs will certainly use custom read functions that are more meaningful when it comes to input errors too.
As others have said delete [] is wrong - and in fact there is no reason to use new in the first place for such a small structure.
Related
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 1 year ago.
I am currently learning how to write a code that prompts the user to define how many players and rounds they want in a dice game, with the additional goal to output the results of both into a file. A couple of resources I have seen have suggested when defining the string variable, you want a secondary string for the sole purpose to "gobble newlines."
Here is the snippet of the code I was looking at:
int main()
{
int nPlayers, nRounds, score;
**string name, dummy;**
cout <<"Enter number of players: ";
cin >> nPlayers;
cout << "Enter number of rounds: ";
cin >> nRounds;
**getline (cin, dummy); // gobble up newline**
ofstream ofs ("scores.txt");
ofs << nPlayers << " " << nRounds << endl;
My question is based around the two lines denoted with double asterisks. Why the need to write a string like this?
Many input streams have extra newline characters between inputs.
"Gobble up a newline" is to get rid of those to get the correct output.
For example:
5 //number of inputs
//empty newline character
89 //first input value
...
The dummy variable is used to store it since it is not of much use to store a newline character.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I tried to do a phone Sys and I used a while loop in the main{}. I don't know why it only runs one time, it suppose to run infinite time unless I give it command to stop.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void record(string name, int phoneNum, int count);
// main
int main() {
cout << " Welcome to use the Phone Contact Systerm " << endl;
string name;
int phoneNum;
int count = 0;
string signToStop;
cout << " Please enter name and phone number " << endl;
while ( cin >> name >> phoneNum){
cout << " If you want to start the program, enter start " << endl;
cout << " If you want to quit the program, enter quit " << endl;
cin >> signToStop;
if (signToStop == "start"){
record(name, phoneNum, count);
}
else if ( signToStop == "quit" ){
break;
}
count++;
}
}
// record all name info into Name set and record all phone numbers into PhoneNum set
void record(string name, int phoneNum, int count){
string Name[] = {};
int PhoneNum[] = {};
Name[count] = {name};
PhoneNum[count] = {phoneNum};
// now start to record all the info into .txt document
ofstream phoneFile;
phoneFile.open("contact.txt");
phoneFile << name << " " << phoneNum << endl;
}
The result is:
Welcome to use the Phone Contact Systerm
Please enter name and phone number
Molly 5307659229
Process finished with exit code 0
Maybe try ulong int for the phone number, it might be too long. Also I might add that I am a bit confused, as your function record() has a 3rd argument that has no default argument. Your problem might lie there too. As without a default you need to put the argument in when it is used.
As spectras said, a phone number is not really an integer, and so it's not a "number" in the programming (or even mathematical) sense.
It's more like a sequence of digits; that is, a string.
You have two problems when you try to interpret it as an int:
Your int type is too small for the value (this is what's causing your loop to end)
Leading zeroes are not meaningful (at best, it's used to flip into octal mode, which is not what you wanted).
I'd instead read it as a string. You can still validate it later, like "is every character a digit?".
Introduction
I am trying to code a converter for bin/oct/dec/hex numbers in c++. At first I print a message in a console asking the user to insert the type of conversion he wants to do and, followed by the cin that allows him to enter the conversion and then i ask him for the number followed by the cin that allows him to enter the number.
My problem
My problem is that after the user inserts the conversion, the variable gets printed on the console without me telling it that.
What I've Tried
I looked on the docs and in their example they do it like this:
cout << "Please enter an integer value: ";
cin >> i;
cout << "The value you entered is " << i;
cout << " and its double is " << i*2 << ".\n";
And that is similar to my code(which you will see below).
I also tried to do getline(cin, type) but still the variables would get printed without me coding that.
My code
Faulty code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string type;
int n;
cout << "Insert what type of conversion you want to make(binoct, bindec, binhex, octbin, octdec, octhex, decbin, decoct, dechex, hexbin, hexoct, hexdec): ";
cin >> type;
cout << "Insert the number you want to convert: ";
cin >> n;
return 0;
}
Input
binoct
1001
Output
Insert what type of conversion you want to make(binoct, bindec, binhex,octbin, octdec, octhex, decbin, decoct, dechex,hexbin, hexoct, hexdec):binoct
binoct
Insert the number you want to convert:1001
1001
Expected output:
Insert what type of conversion you want to make(binoct, bindec, binhex,octbin, octdec, octhex, decbin, decoct, dechex,hexbin, hexoct, hexdec):binoct
Insert the number you want to convert:1001
Additional notes
I should mention that before this version of the code I did use cout to print my variables to see if it works but i re-built the code a few times and now there's no cout << type or cout << n inside my code
I looked on stackoverflow and I didn't seem to see anything similar, if this is a duplicate I apologize.
The code is fine, either clean and rebuild your project, or it has something to do with your project / debug settings, that print out the value.
Try Building and Running the Program in release mode.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have a Structure
struct StudentRecord{
char StudentFamilyName[20]
}gRecs[50];
cout << "Family Name: ";
cin >> gRecs[50].StudentFamilyName;
char str[20];
str[20] = toupper(gRecs[i].StudentFamilyName[0]);
cout << str;
What i want to do is to store the first letter of family name as
upper case and the rest as lower case? How do I do that?
I used toupper but when I implement it doesnot work. Could anyone help me out? Thank you.
Note: This was an exam question.
Here's how to capitalize a string using character arithmetic:
#include <iostream>
#include <string>
using namespace std;
string ToCapitalize(string input)
{
if (input.length() > 1 && input[0] >= 'a' && input[0] <= 'z')
{
input[0] -= 32;
}
return input;
}
int main() {
std::string StudentFamilyName("smith");
cout << StudentFamilyName << std::endl;
cout << "Capitalized: " << ToCapitalize(StudentFamilyName) << endl;
}
Your problem isn't with toupper. There are a couple of them, actually.
cin >> gRecs[50]
gRecs is size 50, so index 50 is out of bounds. To insert into the first record you would use
cin >> gRecs[0].StudentFamilyName;
Second record: gRecs[1], etc.
Next,
char str[20];
str[20] = toupper(str[0]);
You declare str in which nothing is populated, and then call toupper on it.
And the index ([20]) is the 21st character (which is out of bounds). You are attempting to convert the 21st character in the str toupper.
What you need is something like:
// i is the index into your student records array, possibly in a loop
cin >> gRecs[i].StudentFamilyName;
gRecs[i].StudentFamilyName[0] = toupper(gRecs[i].StudentFamilyName[0]);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have a visual c++ project named Search Elements in which there is a class called PeriodicTable and I have another visual c++ project called Write Elements in which there is this same class and it's description(variable names and their sizes) is same too...
I use the Write Elements project to write the object of the class Periodic Table to a binary file named PeriodicTable.dat but whenever I use the binary file with my Search Elements project(basically just copy-paste from Write Elements to Search Elements) then the output is unexpected(contains garbage value).
In my opinion the file should work with both the projects as both the projects contains the same class decription. But I don't know what is the problem???
Write Elements Code:
#include <iostream>
#include <fstream>
using namespace std;
class PeriodicTable
{
char Name[15], Symbol[3], Block, State[10], Colour[15], Classification[20];
int GroupNo, AtomicNo, PeriodNo;
float Weight;
public:
void GetInfo();
};
int main()
{
PeriodicTable ptele;
ofstream fileout;
fileout.open("PeriodicTable.dat", ios::binary | ios::app);
system("cls");
ptele.GetInfo();
fileout.write((char *)&ptele, sizeof(ptele));
fileout.close();
return 0;
}
void PeriodicTable::GetInfo()
{
cout << "Full Name of the element: ";
cin >> Name;
cout << "Symbol: ";
cin >> Symbol;
cout << "Block: ";
cin >> Block;
cout << "State(at Room Temperature): ";
cin >> State;
cout << "Colour: ";
cin >> Colour;
cout << "Classification: ";
cin >> Classification;
cout << "Group Number: ";
cin >> GroupNo;
cout << "Atomic Number: ";
cin >> AtomicNo;
cout << "Period Number: ";
cin >> PeriodNo;
cout << "Atomic Weight: ";
cin >> Weight;
}
You did not perform class abstraction correctly. And more over, everything in same file? including class definition? That's not how you use VS project structure.
I assume you want to create two separate applications. One would create periodic table and a second application use the file generated by first application.
If above is correct, you need to declare the PeriodicTable class in header, implement constructor, destructor and GetInfo method in a .cpp implementation. Another .cpp implementation should contain your main() function for the first application.
Note that it is generally a good idea to create a universal header file in a shared location by two applications which contain global definitions, like the path to the generated .dat file. In this case, absolute path should be taken as both applications will unlikely have same relative path to the file.
Another thing to notice, instead of letting compiler figure out how the file should be structured, structure it yourself. Follow the structure convention you created in both application. One suggestion is that instead of writing (char *) &ptele, write one line for one element, give a tab between each column, say between Element and Symbol. You'll need to parse it properly before using the value but this avoids any ambiguity of the data.
It perfectly works for me with the following read code:
int Read()
{
ifstream file;
file.open("PeriodicTable.dat", ios::binary | ios::in);
while (0 == file.rdstate())
{
PeriodicTable ptele;
file.read((char *)&ptele, sizeof(ptele));
//if (0 == file.rdstate())
// ptele.PrintInfo();
}
file.close();
return 0;
}
I do not think you use the VS project structure correctly. At the first sight your simple solution should contain one project that would contain one class (PeriodicTable) and this class should have several methods e.g. searchElements, writeElements, readElements etc. What is wrong with this approach? If, for some reason, you cannot use this approach, then I think you should better explain your problem, what you are trying to achieve.