In my program, there will be two lines of output: numbers in the first line are integers less than 1000; numbers in the second line are floats between 0 and 10. The format of the output I want is like:
right format
and here is how I try (all outputs are the last four lines):
case 1 - 5
output without format; in the picture we can see the numbers that should be printed
line 1 without format and line 2 with format
numbers in line 1; only the first one is right, and the number that is bigger than 100 is in scientific notation
both lines with format
just like case 2, and <<setw(3)<<setfill('0') seems only works for one time to change 43 to 043, and then it won't work any more
With noshowpoint added. If i print *(p + 2)alone, it always prints 118with or without format. But if I print *(p + 2) in the for loop, the output is still 1.2e+002 except for the first one. But if I print the number 118 directly, the output is right.
So, which part of my code is wrong? And what is the right way to output the answer in right format?
Indeed, not all IO Formatting Manipulators are persistent. Some of them, like std::setw only take effect on the next operation, then they expire. There's nothing "wrong" with your code; you just need to use the manipulator again. Refer to your favourite C++ standard library documentation to check the persistence of each manipulator that you use.
Well, for the third, you set showpoint but never unset it with the noshowpoint, hence the next lines issue.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double x[4]= {43.0,118.0,9.0,5.0};
double y[4] = {9.5, 9.0, 8.5, 8.0};
// your code goes here
for (int i=0; i< 4; i++)
{
cout<<noshowpoint<<setprecision(3)<<setw(3)<<setfill('0')<<(x[i]) <<" ";
cout<<showpoint<<setprecision(2)<<y[i] << endl;
}
return 0;
}
gives the desired output.
Just pay attention that you set the showpoint and setprecision manipulators for stream, not for the single output.
Related
Ok so i have been learning binary search. My teacher has given me a problem on codeforces and it always fails on test 2. Here is the problem:
In this problem jury has some number x, and you have to guess it. The number x is always an integer from 1 and to n, where n
is given to you at the beginning.
You can make queries to the testing system. Each query is a single integer from 1
to n
. Flush output stream after printing each query. There are two different responses the testing program can provide:
the string "<" (without quotes), if the jury's number is less than the integer in your query;
the string ">=" (without quotes), if the jury's number is greater or equal to the integer in your query.
When your program guessed the number x
, print string "! x", where x
is the answer, and terminate your program normally immediately after flushing the output stream.
Your program is allowed to make no more than 25 queries (not including printing the answer) to the testing system.
Input
Use standard input to read the responses to the queries.
The first line contains an integer n
(1≤n≤pow(10,6) — maximum possible jury's number.
Following lines will contain responses to your queries — strings "<" or ">=". The i
-th line is a response to your i-th query. When your program will guess the number print "! x", where x
is the answer and terminate your program.
The testing system will allow you to read the response on the query only after your program print the query for the system and perform flush operation.
Output
To make the queries your program must use standard output.
Your program must print the queries — integer numbers xi
(1≤xi≤n), one query per line (do not forget "end of line" after each xi
). After printing each line your program must perform operation flush.
And here is my code:
#include <iostream>
using namespace std;
int main()
{
int n;
string s;
int k=0;
cin>>n;
int min=1,max=n;
int a;
while(k==0)
{
if(max==min+1)
{
cout<<"! "<<min;
k=1;
break;
}
a=(min+max)/2;
cout<<a<<endl;
cin>>s;
if(s==">=")
min=a;
else
max=a;
}
}
I dont know what test 2 is, but i would be happy to hear ideas as to where my programs is wrong. My guess is its something with the number of guesses. Thanks in advance!
I have tried variations of the loop written above, but they all give the same result.
Not sure if the title is properly worded, but what I am trying to ask is how would you signify the end of input for an array using newline. Take the following code for example. Not matter how many numbers(more or less) you type during the input for score[6], it must take 6 before you can proceed. Is there a method to change it so that an array can store 6 or 100 variables, but you can decide how many variables actually contain values. The only way I can think of doing this is to somehow incorporate '\n', so that pressing enter once creates a newline and pressing enter again signifies that you don't want to set any more values. Or is something like this not possible?
#include <iostream>
using namespace std;
int main()
{
int i,score[6],max;
cout<<"Enter the scores:"<<endl;
cin>>score[0];
max = score[0];
for(i = 1;i<6;i++)
{
cin>>score[i];
if(score[i]>max)
max = score[i];
}
return 0;
}
To detect "no input was given", you will need to read the input as a input line (string), rather than using cin >> x; - no matter what the type is of x, cin >> x; will skip over "whitespace", such as newlines and spaces.
The trouble with reading the input as lines is that you then have to "parse" the input into numbers. You can use std::stringstream or similar to do this, but it's quite a bit of extra code compared to what you have now.
The typical way to solve this kind of problem, however, is to use a "sentry" value - for example, if your input is always going to be greater or equal to zero, you can use -1 as the sentry. So you enter
1 2 3 4 5 -1
This would reduce the amount of extra code is relatively small - just check if the input is -1, such as
while(cin >> score[i] && score[i] >= 0)
{
...
}
(This will also detect end-of-file, so you could end the input with CTRL-Z or CTRL-D as appropriate for your platform)
I'm learning c++ and got the project to send a pascal's triangle to output (after n-rows of calculation)., getting output like this, stored in a stringstream "buffer"
1
1 1
1 2 1
1 3 3 1
But what I want is rather
1
1 1
1 2 1
1 3 3 1
My idea was: calculate the difference of the last line and current line length (I know that the last one is the longest). Then pad each row using spaces (half of the line-length-difference).
My Problem now is:
I didn't get how getLine works, neither how I might extract a specific (-> last) line
I don't know and could not find how to edit one specific line in a stringstream
Somehow I got the feeling that I'm not on the best way using stringstream.
So this is rather a common question: How'd you solve this problem and if possible with stringstreams - how?
To know the indentation of the first line, you would need to know the number of lines in the input. Therefore you must first read in all of the input. I chose to use a vector to store the values for the convenience of the .size() member function which will give the total number of lines after reading in all input.
#include<iostream>
#include<sstream>
#include<vector>
#include<iomanip> // For setw
using namespace std;
int main()
{
stringstream ss;
vector<string> lines;
string s;
//Read all of the lines into a vector
while(getline(cin,s))
lines.push_back(s);
// setw() - sets the width of the line being output
// right - specifies that the output should be right justified
for(int i=0,sz=lines.size();i<sz;++i)
ss << setw((sz - i) + lines[i].length()) << right << lines[i] << endl;
cout << ss.str();
return 0;
}
In this example, I am using setw to set the width of the line to be right justified. The padding on the left side of the string is given by (sz - i) where sz is the total number of lines and i is the current line. Therefore every subsequent line has 1 less space on the left hand side.
Next I need to add in the original size of the line (lines[i].length()), otherwise the line will not contain a large enough space for the resulting string to have the correct padding on the left hand side.
setw((sz - i) + lines[i].length())
Hope this helps!
If you have access to the code that writes the initial output, and if you know the number of lines N you are writing, you could simply do:
for(int i = 0; i < N; ++i) {
for(int j = 0; j < N - 1 - i; ++j)
sstr << " "; // write N - 1 - i spaces, no spaces for i == N.
// now write your numbers the way you currently do
}
i'm trying to build a pyramid with numbers between 1 and the inserted number. For example, if i insert 6 to the integer, that the piramid will be as there:
12345654321
234565432
3456543
45654
565
6
I tried using a for loop but i get in any line one or ++ numbers to 6.
This is the code:
#include<stdio.h>
#include <iostream>
#include <conio.h>
int main()
{
int i,j,d;
std::cin >> d;
for(i=1;i<=d;i++)
{
for(j=1;j<=i;j++)
printf("%d",j);
printf("\n");
}
getch();
return 0;
}
How can i solve this problem building a pyramid like the shown.
Since this is homework, I won't paste an algorithm, but here's a few hints:
This 12345654321 can be printed by counting from one to six and then back to one.
This __3456543__ means that for numbers smaller than n, you have to output a _ instead, where n depends on the level you are printing.
Define your loop variables within the loop: for(int i=1;i<=d;i++) ... They are only interesting within the loop, and access outside the loop is usually an error, which is then flagged by the compiler.
There's no need to for the getch(); at the end. When you're in the debugger, you can put a breakpoint on the last line. If you aren't you don't want to have to press a key just to end your program.
If you use std::cout << j and std::cout << '\n' for outputting, you don't need printf() either. (Once you want formatting, many will tell you that printf format strings are easier. I don't believe that, but would accept it, if it weren't that you can crash any application with an ill-formed printf format string, while it's much harder to come up with a way to crash your app using streams.)
There you go:
for(j=i;j<=d;j++)
Also you forgot about formatting and the right side of the pyramid, but I think that's out of scope for this question and you can figure the code yourself :)
Try to have the first line working the way you want.
Repeat it d times, where d is the number entered by the user.
Notice that on line l, numbers < l are replaced by spaces.
Consider this: you have D rows, 1..D. Six rows means your rows are numbered 1 to 6. Now, for each row d:
print d-1 space characters. First row has no spaces, second has one and so on.
print the numbers d..D. So on the first line you print 1..6, on the second you print 2..6.
print the numbers D-1..d. So on the first line you print 5..1, on the second you print 5..2
print a new line
To simplify, I'm trying to read the content of a CSV-file using the ifstream class and its getline() member function. Here is this CSV-file:
1,2,3
4,5,6
And the code:
#include <iostream>
#include <typeinfo>
#include <fstream>
using namespace std;
int main() {
char csvLoc[] = "/the_CSV_file_localization/";
ifstream csvFile;
csvFile.open(csvLoc, ifstream::in);
char pStock[5]; //we use a 5-char array just to get rid of unexpected
//size problems, even though each number is of size 1
int i =1; //this will be helpful for the diagnostic
while(csvFile.eof() == 0) {
csvFile.getline(pStock,5,',');
cout << "Iteration number " << i << endl;
cout << *pStock<<endl;
i++;
}
return 0;
}
I'm expecting all the numbers to be read, since getline is suppose to take what is written since the last reading, and to stop when encountering ',' or '\n'.
But it appears that it reads everything well, EXCEPT '4', i.e. the first number of the second line (cf. console):
Iteration number 1
1
Iteration number 2
2
Iteration number 3
3
Iteration number 4
5
Iteration number 5
6
Thus my question: what makes this '4' after (I guess) the '\n' so specific that getline doesn't even try to take it into account ?
(Thank you !)
You are reading comma separated values so in sequence you read: 1, 2, 3\n4, 5, 6.
You then print the first character of the array each time: i.e. 1, 2, 3, 5, 6.
What were you expecting?
Incidentally, your check for eof is in the wrong place. You should check whether the getline call succeeds. In your particular case it doesn't currently make a difference because getline reads something and triggers EOF all in one action but in general it might fail without reading anything and your current loop would still process pStock as if it had been repopulated successfully.
More generally something like this would be better:
while (csvFile.getline(pStock,5,',')) {
cout << "Iteration number " << i << endl;
cout << *pStock<<endl;
i++;
}
AFAIK if you use the terminator parameter, getline() reads until it finds the delimiter. Which means that in your case, it has read
3\n4
into the array pSock, but you only print the first character, so you get 3 only.
the problem with your code is that getline, when a delimiter is specified, ',' in your case, uses it and ignores the default delimiter '\n'. If you want to scan that file, you can use a tokenization function.