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.
Related
I am right now learning about making a program using Borland, so this is my first time on use it. I got confused by the result, cause the result is not what I expected.
Below is my code:
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
char nama[25];
char kelas[5];
char jurusan[30];
char universitas[30];
char alamat[30];
cout<<"Masukkan Nama Anda\t : ";
gets(nama);
cout<<endl;
cout<<"Kelas\t\t\t : ";
gets(kelas);
cout<<endl;
cout<<"Jurusan\t\t\t : ";
gets(jurusan);
cout<<endl;
cout<<"Universitas\t\t : ";
gets(universitas);
cout<<endl;
cout<<"Alamat\t\t\t : ";
gets(alamat);
cout<<endl;
cout<<"\n\tBIODATA ANDA SEBAGAI MAHASISWA ADALAH SEBAGAI BERIKUT:"<<endl;
cout<<"\n\nNama\t\t\t : "<<nama<<endl;
cout<<"Kelas\t\t\t : "<<kelas<<endl;
cout<<"Jurusan\t\t\t : "<<jurusan<<endl;
cout<<"Universitas\t\t : "<<universitas<<endl;
cout<<"Alamat\t\t\t : "<<alamat<<endl;
cout<<"\n\nSilahkan tekan tombol ENTER untuk keluar dari program biodata singkat ini!";
getch();
}
The result I got is kinda fine, but there is still one problem that I got here. Which there is one variable that don't show what the value of the user already gave, it did not show the value, it even just gave the word "u" which I don't understand from where this word was coming. I sent it with my picture, so you can see it.
I hope you would help me, and thank you very much for reading my problem.
All of your input arrays:
char nama[25];
char kelas[5];
char jurusan[30];
char universitas[30];
char alamat[30];
are going to be one continuous block of chars. Your input methods will easily overflow from one array to the next causing all sorts of havoc.
Try using std::string instead and input from std::cin:
std::string nama;
std::string kelas;
std::string jurusan;
std::string universitas;
std::string alamat;
std::cout << "Masukkan Nama Anda\t : ";
std::cin >> nama;
std::cout << std::endl;
std::cout <<"Kelas\t\t\t : ";
std::cin >> kelas;
std::cout << std::endl;
std::cout << "Jurusan\t\t\t : ";
std::cin >> jurusan;
std::cout <<std::endl;
std::cout << "Universitas\t\t : ";
std::cin >> universitas;
std::cout <<std::endl;
std::cout << "Alamat\t\t\t : ";
std::cin >> alamat;
std::cout << std::endl;
After i tried some several suggestion to solve my own problem. Then i wonder, why there is just the variable of Jurusan which contain character that i don't know where it comes from. I tried to see it again, and then i reverse the place of another variable, also i put a comment sign //comment to make it not being seen as a code by machine in front of the Jurusan variable there is no problem anymore. Quite thinking, and then i just tried to count the sum of character in a variable which exactly below the Jurusan variable(Universitas variable), and then i also count the size of that variable(Universitas variable).
After this i just realised if the word "u" which in the variable Jurusan is the rest of the characther which comes from the variable below the Jurusan variable, which variable Universitas.
I am as the user, put the characther greater than the size of Universitas variable. And of course, that is wrong, and a mistake.
I came back to the code, and make the size of the variable Universitas is greater than before, and right now the problem is solved. And you guys can see it in my picture below if that is already succed, you also can compare it with the previous picture that i sent here in the Question section which has problem.
So, thank you guys for you who tried to help me. Cheers!
For my homework project I'm expected to create a program that asks the user their favorite city and which character they would like to display. The user inputs a number representing the position of the character within the city they would like to display, and the program is supposed to display the letter at this position.
We have not yet learned how to extract characters from a string, but this part of our project is supposed to show that we can properly google to find solutions for our coding. I have found a void function that would extract the character from a specific position for me, but am entirely lost on how to use it. I've tried several different methods and typed out every way I could possibly think to implement this function and it has not worked.
I've tried copying the example code I found online exactly as is (first example found at this address: https://www.geeksforgeeks.org/string-at-in-cpp/) but even the example would not run in visual studio 2017.
#include <iostream>
#include <string>
using namespace std;
void at(string);
int main()
{
//variables for favorite city & display character
string favCity;
int dispChar;
//asking user for favorite city
cout << "Input your favorite city: ";
cin >> favCity;
cout << "Which character would you like to display: ";
cin >> dispChar;
cout << endl << endl;
cout << "The user entered: " << favCity << endl;
cout << "The character at position " << dispChar << " is: " << at();
}
The expected result is that the computer will display "The character at position (dispChar) is: (whatever letter is at the user input position dispChar)"
EX: "The character at position 2 is: e //If the user input the city Detroit
I get the error that at is undefined, when I tried using str.at(); I would get str is undefined, etc.
There is no need of using an external function in order to extract a character from a string by its index. std::string itself implements an std::string::at function and also overloaded [] operator.
So two ways for doing that:
1.
cout << "The character at position " << dispChar << " is: " << favCity.at(dispChar);
2.
cout << "The character at position " << dispChar << " is: " << favCity[dispChar];
std::string::at can be used to extract characters by characters from a given string.
char& string::at (size_type idx)
string::at function returns the character at the specific position(idx). You can directly use string::at as you have included class.Learn More Here
So, in your solution you declared void at(string); therefore you need to define it too.
I have made some changes in your code I think that should do it.
#include <string>
using namespace std;
void extract_char(string str, int pos)
{
cout<<str.at(pos);
}
int main(void)
{
int dispChar;
string favCity;
cout<<"Input your favorite city: ";
cin>>favCity;
cout<<"Which position would you like to extract the character from(0 to size of city): ";
cin>>dispChar;
cout<<endl<<endl;
cout<<"The user entered: "<<favCity<<endl;
extract_char(favCity, dispChar-1);
/*
OR
cout<<"The character at position "<<dispChar<<" is: "<<favCity.at(dispChar-1);
*/
return 0;
}
'strToDouble' was not declared in this scope Lab1-3.cpp /Lab1-3/src line 65 C/C++ Problem
The first problem, as #SoronelHaetir pointed out, is that you were trying to assign title to variable which can only hold one character. Instead, you should use char array, char pointer, or even string object to contain your multi-letter value. In my code example below, I used char array with fixed size of 25, to store the title. Beware that you can store only up to 24 characters in it, because char arrays need special character which will denote the end of char array. Otherwise it would end up writing junk after your desired value. That special character is null-terminating character which is written like '\0'.
Using return; statement in your void displayBid(Info itemOne); function was completely unnecesary. While you can use return; to stop function from executing, you placed it at the end of function which was just about to end itself in normal way, but you forced it with no reason. Besides, you do not need any return; statements for functions which return void – nothing.
Then, fund and bidAmount are representing money value, which may or may not be of integer value, so you should consider float or double data types to store money value.
Next thing is your function Info getBid();. First, I have to say that naming may be a bit confusing. If you read the name of that function without seeing its actual code, how would you understand what it may do? For me, it sounded like it is about to get me information about a bid, while actually it is setting it up. Second, you could simplify code for entering values, in the way I did it in my code example. The way you tried to use different techniques for getting values from user input was a bit wrong. getline is member function which is used with istream objects. Your istream object is cin. In order to access that member function you shall write it as cin.getline(to be discussed);. That function only works with characters. Its first parameter accepts pointer to the first character (address of the first character) in sequence of characters.
Second parameter is of integer data type and specifies how much characters you want to be extracted from your input and stored in an argument which is in place of the first parameter. Beware not to write, for example, 25, because in char array you have to leave one place for '\0' character, which is automatically placed where it needs to be. getline member function has also default delimiter '\n', which denotes new line. It means that you can enter less characters than function can extract, because extraction will stop as soon as it reads that delimiter value from user input. Although, if you want your specific delimiter, getline member function has its overloaded version which third parameter is one where you enter desired delimiter as an argument. (Overloaded functions are basically functions with the same name, but different parameters. They provide same functionality with different implementation.)
Even if you had set up values for a bid, you never returned it from function. You correctly said that its return value is Info, but you did not return it. Actually, you again exited just before its normal exit. Instead, you should have written return itemOne; In my code example, I passed the variable created in int main(); function by reference, which means it is not a copy as usually, so I do not have to return it and assign to another variable of the same type to appropriately apply desired changes.
Finally, in the int main(); function, you could just declare int choice, without initializing it and use do-while loop in the way I did it. Also, switch statement provides defining what will happen if none of the cases are true, in the way that after all cases you write default:, and below it whatever you want to happen. In your code example, your function will continue executing even if user enters anything but 1, 2 except for 9 defined to stop its execution. In my code example, whatever user enters besides 1 and 2, including zero, function will exit. Well, except for new line.
And, let us discuss again the naming. Your data structure name has to directly imply what it is. Info does not do that. That name would actually be more appropriate for your void displayBid(Info itemOne); function to be called. In my code example, I renamed it to Bid.
#include <iostream>
using namespace std;
struct Bid
{
char title[25];
int vehicleID;
double fund;
double bidAmount;
};
void GetBid(Bid item)
{
cout << "Title: " << item.title << endl;
cout << "Fund: " << item.fund << endl;
cout << "Vehicle: " << item.vehicleID << endl;
cout << "Bid Amount: " << item.bidAmount << endl;
}
void SetBid(Bid & item)
{
cout << "Enter title: ";
cin >> item.title;
cout << "Enter fund: ";
cin >> item.fund;
cout << "Enter vehicle ID: ";
cin >> item.vehicleID;
cout << "Enter amount: ";
cin >> item.bidAmount;
}
int main()
{
Bid item;
int choice;
do {
cout << "Menu:" << endl;
cout << " 1. Enter Bid" << endl;
cout << " 2. Display Bid" << endl;
cout << " 0. Exit" << endl;
cout << "Enter choice: ";
cin >> choice;
switch (choice)
{
case 1:
SetBid(item);
break;
case 2:
GetBid(item);
break;
default:
choice = 0;
cout << "Goodbye." << endl;
break;
}
} while (choice != 0);
return 0;
}
The first (and biggest) problem is:
char title;
This allows you to store only a single character rather than an entire name (prefer std::string to char arrays).
Why does trying to input two strings using cin.get() fails? I can successfully read the first string but the input fails for second string and subsequent operations.. See the code:
#include <iostream>
#include <stdlib.h>
int main(){
long int n,k;
char a[11],b[11];
cin.get(a,11);
n = atoi(a);
cin.get(b,11);
cout<<b;
k = atoi(b);
cout << "\ncin.rdstate(): " << cin.rdstate()
<< "\n cin.eof(): " << cin.eof()
<< "\n cin.fail(): " << cin.fail()
<< "\n cin.bad(): " << cin.bad()
<< "\n cin.good(): " << cin.good() << endl << endl;
}
I am trying to input two strings and store them into long int variables as shown in program, but the cin.get(b,11) fails and stack overflow occurs for
k= atoi(b) .Also, you may observe nothing is output for cout<<b .. And, at last cin.fail() is set to 1 , which means I am doing some kind of logical error.. Please help me in rectifying this!
Please suggest some method which is fast and meant for c++ only ..
(If you feel this question is too bad please mention in comments before down voting this, I am already struggling at 21 rep!)
\n will remain in the buffer after the first cin. You can solve this problem by adding an empty cin.get()
cin.get(a,11);
n = atoi(a);
cin.get();
cin.get(b,11);
cout<<b;
k = atoi(b);
cin.get() Does not extract the delimiter from the input (documentation).
If you are C++ with streams it makes sense to use the built in functionality. In particular, C++ offers formatted I/O. To read two numbers you should use:
long int a, b;
cin >> a;
cin >> b;
This will read two numbers from the standard input.
If speed is a concern, try to turn off C I/O synchronisation: std::ios::sync_with_stdio(false); There is an interesting benchmark here that shows that if you turn of synchronisation with C I/O, streams are actually pretty fast.
I use Visual C++ 2010 Express Edition to compile and run the .exe files I write in the C++ programming language. I am trying to create a loop-based logic using C++ to ask the user how many entries he chooses to enter, and ask questions limited to that no. of entries. For example I want to output, "How many characters do you wish to enter?: " Say the user gives the answer as '3' which is stored in the int variable 'entries'. I then want to keep asking the question 3 times before it stops and continues with the next line of code. I hope you understand, here is a block of code to demonstrate what I am doing:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "How many values do you need to enter?: ";
int entries;
cin >> entries;
int offset, number;
string valueName[50];
float valueValue[50];
for (offset = 0; offset < entries; offset++)
{
cout << "Enter " << number << " Value Name: ";
cin >> valueName[offset];
cout << "Enter " << valueName[offset] << "\'s value: ";
cin >> valueValue[offset];
for (number = 1; number <= entries; number++)
{
}
}
char response;
cin >> response;
return 0;
}
Strangely when I run this simple program, it fails when I enter the value's name to be inserted into the 0th element of the valueName[] array. It just pauses the execution of the program and a dialog box pops up saying "Runtime Check Failure #3 - Variable 'number' is being used without being initialized!" Another problem regarding this program is that, for quite some time, when I ran this program this "Runtime Check Failure #3" box never appeared, and when it didn't, the number value went wrong, and first started with 1, and then for the next loop jumped to 6, and then repeated 6 again for the next loop! Please help me! I've checked online scouring this problem everywhere, but it just doesn't apply to my type of problem! Is it because the variables are out of scope? But they're declared outside the for loops right? So please help me!
The runtime is telling you the truth, the following line comes after you have declared number as an int but have not given it a value.
cout << "Enter " << number << " Value Name: ";
In your code you declare the following, in C++ this means give me 2 ints but the values are not defined yet, e.g.
int offset, number;
Change it to something like this ..
int offset = 0;
int number = 0;
You are printing the variable number without assigning to it first, i.e. it's uninitialized. When it prints some random number it's because that what happens to be in the memory at the time you run the program. Assign a value to it before you use it.
The problem is exactly the error message you're getting. You're using the variable number without initializing it.
You use the variable right here, at the top of your loop, when it hasn't been initialized to anything yet:
cout << "Enter " << number << " Value Name: ";
What is your intention with the number variable? It doesn't really seem to be serving any purpose. If you want to print which entry you're currently on, you could use the offset variable instead, like this:
cout << "Enter " << offset << " Value Name: ";
But that still seems a little unclear to me.
But the reason that you're having a problem is because the value is uninitialized, so you're experiencing undefined behavior. This is also the reason that Visual Studio doesn't always catch it; it will probably always catch in Debug mode, but in Release mode it will almost never catch it. You need to initialize all your variables before you use them.
In my case it was because an extern variable was declared twice.