C++ output formatting using setw and setfill - c++

In this code, I want to have numbers printed in special format starting from 0 to 1000 preceding a fixed text, like this:
Test 001
Test 002
Test 003
...
Test 999
But, I don't like to display it as
Test 1
Test 2
...
Test 10
...
Test 999
What is wrong with the following C++ program making it fail to do the aforementioned job?
#include<iostream>
#include<string>
#include<fstream>
#include<iomanip>
using namespace std;
const string TEXT = "Test: ";
int main()
{
const int MAX = 1000;
ofstream oFile;
oFile.open("output.txt");
for (int i = 0; i < MAX; i++) {
oFile << std::setfill('0')<< std::setw(3) ;
oFile << TEXT << i << endl;
}
return 0;
}

The setfill and setw manipulators is for the next output operation only. So in your case you set it for the output of TEXT.
Instead do e.g.
oFile << TEXT << std::setfill('0') << std::setw(3) << i << endl;

Related

endl, '\t' and '\n' dont work after 15 tabs

If you compile and run this code, the endl doesn't get executed. You will get 0hello when you pop the terminal into full screen.
#include <iostream>
int main() {
using namespace std;
for (int i = 0; i < 15; i++) {
cout << '\t';
}
cout << "0" << endl << "hello";
return 0;
}
However, if you use cout << "00" << endl << "hello"; then it works fine. I don't understand why this happens nor how to fix it.
I am assuming you are running this from visual studio where the default terminal width is 120 characters.
A tab is 8 characters. 8x15 = 120.
If you look at the output, there is a blank line before the 0. It is printing the tabs: just that you've reached the end of line so it has moved to the next line.
If you change the terminal width to 80 characters you might get a different result - a blank line and the 0 in the centre of the page.

Stringing together multiples of the same string (an asterisk) determined by an input file. C++

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;
//...

removing namespace std specifically sprintf in a denary to hex C++ program

I have coded a denary to hex converter and am trying to find a way to remove the sprinf built in function as well as the stoi built in function that i used because as i am using c++ more i am told that using namespace std is bad practice but i cannot think of a way of doing this without breaking my program any help would be appreciated.
also i have left my comments in my code for future Questions should i remove these or leave them in when posting thankyou
#include <iostream>
#include <string>
#pragma warning(disable:4996)
using namespace std;
int DecToHex(int Value) //this is my function
{
char *CharRes = new (char); //crestes the variable CharRes as a new char
//sprintf is part of the standard library
sprintf(CharRes, "%X", Value);
//char res is the place the concerted format will go
//value is the value i want to convert
//%X outputs a hex number
//snprintf covers the formatting of a string
int intResult = stoi(CharRes); //stoi is a function in the library
std::cout << intResult << std::endl; //print int results to the screen
return intResult; //returns int result
}
int main()
{
int a;
std::cout << "Please enter a number" << std::endl;
std::cin >> a; //stores the value of a
DecToHex(a); //runs the function
system("pause"); //pauses the system
return 0; //closes the program
}
Stream in C++ already have built in function for converting format like decimal /hexa etc .. so you can just do this :
int main()
{
int a;
std::cout << "Please enter a number" << std::endl;
std::cin >> a; //stores the value of a
std::cout << std::hex; // Set the formating to hexadecimal
std::cout << a; // Put your variable in the stream
std::cout << std::dec;, // Return the format to decimal. If you want to keep the hexa format you don't havr to do this
std::cout << std::endl; // Append end line and flush the stream
/* This is strictly equivalent to : */
std::cout << std::hex << a << std::dec << std::endl;
system("pause"); //pauses the system
return 0; //closes the program
}
Using std::hex in the stream will print the value in hexa. Using std::dec will print the value in decimal format. Using std::octa will print the value in octal format.
You can call any function from the standard library without using using namespace std simply by prefixing the function with std::.
For example, std::snprintf, std::stoi etc..

unable get output on the same line with space in between the two output in c++

This is my code
#include<iostream>
using namespace std;
int main()
{
int s,count1;
long long N,R,max1;
cin>>s;
for (int i=0; i<s; i++)
{
cin>> N>>R;
}
cout<< N << R <<endl;
return 0;
}
for input
1
5 6
output
56
but I want the output as
5 6
I am good in c know how to do the same in c,now started learning c++ please help
The way the output stream is being read as is, it is printing the characters contained in N and R consecutively. You need to specify to print a space/tab. Your output line should be:
cout<< N << " " << R <<endl;
That will put a space between the two characters. If you want a tab (which might be nice if you're doing multiple lines of output and want everything to be lined up nicely), replace " " with "\t".
If you want a space to be outputted, then output one!
cout << N << R << endl says output N, output R and then output a newline and flush the buffer. If you want a space, you need to add it to the output:
cout<< N << ' ' << R <<endl;

Cannot find the end of an array when opening a file

So I want to open a file and display the contents. Thing is, I don't know how many elements are used and how many elements are empty. So, when I try to display the elements the first few are shown but the rest are random numbers. How do I find and display the exact number of elements?
file:
10011 Ali Doha 12355555 11-5-14 3434 7890
10015 Ahmed Al-Khor 51244444 13-6-14 3425 4455
10014 Mohammed Al-Wakra 53344333 17-7-14 5566 1234
10012 Omar Doha 56666666 10-8-14 1234 5678
10013 Youssef Al-Khor 7555512 5-5-14 88000 4532
10019 Hamad Al-Wakra 81234567 8-6-14 3125 1265
10018 Jassim Doha 86753541 9-7-14 9875 5566
code:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
const int isize=10;
ifstream datafile;
datafile.open("D:\customers.txt");
int customer_number[isize];
string customer_name[isize];
string customer_address[isize];
long contact[isize];
string Due_date[isize];
int water_consumption[isize];
int electricity_consumption[isize];
double total_bill[isize];
if (!datafile)//to know if the file is exist or not
cout << "error" << endl;
else
{
for(int i=0; i<1000; i++)
{
datafile >> customer_number[i];
datafile>> customer_name[i];
datafile>> customer_address[i];
datafile>> contact[i];
datafile>> Due_date[i];
datafile>> water_consumption[i];
datafile>> electricity_consumption[i];}
}
for(int i=0; i<isize; i++)
{
if(customer_number[i] == '\0')
break;
else
cout << customer_number[i] << "\t" << customer_name[i] << "\t" << customer_address[i] << "\t" << contact[i] << "\t"
<< Due_date[i] << "\t" << water_consumption[i] << "\t" << electricity_consumption[i] << "\t" << endl;
}
datafile.close();
return 0;
}
Looks like each text line is a record, thus use std::getline with std::string to read a record.
When the number of records is unknown, you need a dynamic container, such as std::vector, std::list or std::map, not a fixed size array.
You will need to research the std::string methods and also std::istringstream for parsing the text line into native format fields. There are lots of examples on StackOverflow on how to do this.
So stop using fixed size arrays and use std::vector instead.