FYI I'm a beginner in C++. This is just a part of the complete code, the problem is the 'student.id', if the input starts with '0' e.g.'06042010', the output shows no zero(in this case would be '6042010'! And the point is, I want that first zero to be shown. Thanks.
#include<iostream>
using namespace std;
struct students
{
char name[15];
char surname[10];
int id;
};
int main()
{
students student;
cout<<"Name: ";
cin>>student.name;
cout<<"Surname: ";
cin>>student.surname;
cout<<"ID: ";
cin>>student.id;
cout<<"\nStudent: "<<student.name<<" "<<student.surname<<" ID "<<student.id<<endl;
return 0;
}
If you need to preserve leading zeros, you should store id as a string and not an int.
If your IDs will always be a particular length, you can use C's printf function instead of streams, which gives you more power;
printf( "Student: %s %s ID %08d\n", student.name, student.surname, student.id );
That will always print 8 digits of ID, and will prefix with 0s as needed (if it was just %8d it would prefix with spaces).
But as already pointed out, you're likely better off storing it as a string, because then you will be able to increase the length of the IDs in the future without needing to adjust all the old IDs.
If you need or want to keep the student id a number for some reason you can also us the following:
#include <iomanip>
const int width = 8; //The length of your student ID numbers
cout << "\nStudent: " << student.name << " " <<student.surname
<< " ID " << setfill('0') << setw(width) << student.id << setfill(' ') << endl;
If your ID numbers are not all the same length you will have to detect how long they are and use the appropriate width in each setw() call.
Related
Essentially, the objective is to read an input file (hence inFile and inFileName) and output a population growth with asterisks representing each 1000 people using an ID (ex. 1375892), going from the year 1900 to 2020 in 20-year increments.
So, 1 asterisk for 1000 people, 3 asterisks for 3000 people, etc. The input file has numbers like 5000 and 7000 that I need to use to calculate the number of asterisks I need (by dividing by 1000). Even with that, I'm trying to figure out the final step in converting asteriskNum (the number of asterisks I need to use) and have it output the string of asterisks, not an integer of how many asterisks I need.
I definitely know I'm missing SOMETHING, but even after asking my teacher and scouring through my textbook and notes, I can't figure out how to solve this specific issue.
#include<iostream>
#include<iomanip>
#include<string>
#include<fstream>
using namespace std;
int main(){
string asterisk = "*";
string firstName;
int PopNum{0};
int year{1900};
int asteriskNum{};
const string INTROLINE{"POPULATION GROWTH \n(each * represents 1000 people)"};
cout << INTROLINE << "\n";
string inFileName="DL8_L5_Morrison.txt";
ifstream inFile{inFileName};
if (inFile){
cout << inFileName << " opened for reading. \n";
inFile >> firstName;
while (not inFile.eof()){
inFile >> PopNum;
asteriskNum = PopNum/1000;
cout << year << " " << asteriskNum << " " << << "\n";
year+=20;
inFile.close();
}
else {
cout << inFileName << " did not open for reading. \n";}
cout<<"Goodbye!\n";
return EXIT_SUCCESS;
}
}
You can use a std::string object and use the constructor that takes a count and character as arguments (constructor version #2 here). This will work with an int for the count argument, but it is better to cast it to a size_t type (or just have the calculated value as a size_t in the first place):
//...
asteriskNum = PopNum/1000;
cout << year << " " << std::string(static_cast<size_t>(asteriskNum), '*') << std::endl;
//...
I was using character arrays to get inputs from the user then display the output afterwards. However, every time I enter values with spaces in between, only the first word before the space is printed.
For instance, this is what I typed:
Customer No.: 7877 323 2332
This will be the output:
Customer No.: 7877
I already searched for possible solutions but I can't seem to find the right solution.
This is my code for reference:
#include<iostream>
using namespace std;
int main()
{
char custNum[10] = " "; // The assignment does not allow std::string
cout << "Please enter values for the following: " << endl;
cout << "Customer No.: ";
cin >> custNum;
cout << "Customer No.: " << custNum << endl;
}
Another option is to use std::basic_istream::getline to read the entire string into the buffer and then remove the spaces with a simple for loop. But when using plain-old character arrays don't skimp on buffer size. It is far better to be 1000-characters too long than one-character too short. With your input, your absolute minimum size of custNum is 14 characters (the 13 shown plus the '\0' (nul-terminating) character. (rough rule-of-thumb, take your longest estimated input and double it -- to allow for user-mistake, cat stepping on keyboard, etc...)
In you case you can simply do:
#include <iostream>
#include <cctype>
int main() {
char custNum[32] = " "; // The assignment does not allow std::string
int wrt = 0;
std::cout << "Please enter values for the following:\nCustomer No.: ";
if (std::cin.getline(custNum, 32)) { /* validate every input */
for (int rd = 0; custNum[rd]; rd++)
if (!isspace((unsigned char)custNum[rd]))
custNum[wrt++] = custNum[rd];
custNum[wrt] = 0;
std::cout << "Customer No.: " << custNum << '\n';
}
}
The two loop counters rd (read position) and wrt (write position) are simply used to loop over the original string and remove any whitespace found, nul-terminating again when the loop is left.
Example Use/Output
$ ./bin/readcustnum
Please enter values for the following:
Customer No.: 7877 323 2332
Customer No.: 78773232332
Also take a look at Why is “using namespace std;” considered bad practice? and C++: “std::endl” vs “\n”. Much easier to build good habits now than it is to break bad ones later... Look things over and let me know if you have questions.
Apart from std::getline, if you are going to use C-style strings, try the following code:
int main() {
char* str = new char[60];
scanf("%[^\n]s", str); //accepts space a a part of the string (does not give UB as it may seem initially
printf("%s", str);
return 0;
}
Also, if you absolutely need it to be a number, then use atoi
int ivar = std::atoi(str);
PS Not to forget gets (!!dangerous!!)
char* str;
gets(str);
puts(str);
cin >> int_variable will stop reading input when it reaches the first character that isn't a valid part of a number. C++ does not consider spaces part of a number, so it stops reading as soon as it encounters one.
You could use std::getline to read into a string instead, then remove the spaces from the string before converting to an integer. Or maybe in this case you don't even need the integer and can leave it as a string.
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;
}
I'm really frustrated. I'm trying to read a txt file which has the following content:
Arenas
Edward
239924731
2525976612
Autry
Richard
527646269
6028236739
Using this code :
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main(int argc, const char * argv[])
{
string line;
string last, first;
int uin, number;
ifstream phoneBook;
phoneBook.open("PhoneBook.txt");
while (!phoneBook.eof()) {
phoneBook >> last >> first >> uin >> number;
cout << last << ", " << first << ", " << uin << ", " << number <<endl;
}
return 0;
}
The output would be the same contact endlessly
Arenas, Edward, 239924731, 2147483647
Arenas, Edward, 239924731, 2147483647
Arenas, Edward, 239924731, 2147483647
Arenas, Edward, 239924731, 2147483647
Arenas, Edward, 239924731, 2147483647
I also tried this version of while loop:
while (phoneBook >> last >> first >> uin >> number) {
cout << last << ", " << first << ", " << uin << ", " << number <<endl;
}
For some reasons, the compiler doesn't even step into the loop. It would just jump to return 0;
Your number values are too big to fit into a four-byte signed integer. Maximum value for that is 2147483647 (2^31 - 1), which is why you get that printing out at the end. (You weren't asking about that issue; I don't know how I noticed it myself!)
But what I'm also wondering about is that extra line that you have in between each record. I found this question that discusses fstreams and delimiters. I wonder if it's getting stuck at the blank line, reading nothing, and then just outputting the same values of last, first, uin, and number.
There may be a different type of error. The best method to use is ios::good:
while (!phoneBook.good()) {
This is what I have to do:
A teacher has asked all her students to line up single file according to their first name. For example, in one class Amy will be at the front of the line and Yolanda will be at the end. Write a program that prompts the user to enter the number of students in the class, then loops to read in that many names. Once all the names have been read in it reports which student wourld be at the front of the line and which one would be at the end of the line. You may assume that no two students have the same name. Input Validation: Do not accept a number less than 1 or greater than 25 for the number of students.
This is what I have so far:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int StudentNum;
cout << "How many student are in the class?\n";
cin >> StudentNum;
char sname[StudentNum + 1][25];
if (StudentNum < 1 || StudentNum > 25)
{
cout << "Please enter a number between 1-25 and try again\n";
return 0;
}
for (int i = 1; i <= StudentNum; i++);
{
cout << "Please enter the name of student #" << i << endl;
cin >> sname[i];
}
for (int output = 0; output <=StudentNum; output++);
{
cout << endl << sname[output] << endl;
}
system ("pause");
return 0;
}
Am I missing something about arrays??
You cannot create such an array because its length has to be known at compile time (i.e., it cannot be the result of an expression such as StudentNum + 1).
You can solve this issue because by the problem definition you know an upper bound for the array size, so you can use that as a compile time constant.
However, this problem can be solved without using an array at all. Read the wording carefully.
Hint for the solution without arrays: Think of the array as a single piece of paper (variable) with all the names written one after another. Not using an array then means that you have to be able to solve the problem without looking at all the names at once. How would you come to the answer if I only allowed you to see the names one by one?
Another hint: The problem is still solvable if there were several trillion students in the class (with unique names no less), i.e. more than could possibly fit in the computer's memory at any one time.
C++ array dimensions must be known at compile time (ie not dependent on user-entered variables at run-time). Use strings instead:
string sname[25];
If you were using something besides char arrays, you could also use a vector.
Think about what the problem statement is actually asking for. Your program only needs to output the first and last names alphabetically. Do you actually need to store all the names to do that?
Just for fun, here's how I would do it. Don't turn this in unless are ready to explain to your teacher how it works.
struct MinMax {
std::string min;
std::string max;
MinMax& operator+(const std::string& kid) {
if( min.empty() || kid < min) min = kid;
if( max.empty() || kid > max) max = kid;
return *this;
}
};
int main() {
int nKids;
std::cout << "How many students? " << std::flush;
std::cin >> nKids;
std::cout << "Enter students' names, followed by EOF\n";
MinMax mm(std::accumulate(
std::istream_iterator<std::string>(std::cin),
std::istream_iterator<std::string>(),
MinMax()));
std::cout << mm.min << ", " << mm.max << "\n";
}