So I am currently going through Accelerated C++ course on udemy by Jeremy Siek and I was on that tutorial which he is mentioning string concatenation and in one part he gave task to print something (WITHOUT USING NESTED LOOPS) like this:
OUTPUT:
*
**
***
****
(- So I know about for loops from earlier and I am not completely new to C++ programming, but I am just complementing knowledge from earlier and I know that this problem can be solved with nested for loops. But THIS IS NOT MY QUESTION, KEEP READING, BECAUSE I HAVE TO MAKE INTRO INTO MY QUESTION)
Before he made program which is source code like this (WHICH I COMPLETE UNDERSTAND)
int main()
{
cout << "Please enter your name:";
string name;
cin>>name;
string greeting="Hello, " + name + "!";
string spaces(greeting.size(), ' ');
string stars(greeting.size(), '*');
cout << "**" stars << "**" << endl;
<< "* "<< spaces << " *"<< endl;
<< "* "<< greeting << " *"<< endl;
<< "* "<< spaces << " *" <<endl;
<< "**" stars << "**" << endl;
return 0;
}
Now, about my question: I was trying to do that task he gave, and I came up with something like this:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string star="*";
int br=1;
cout<<star<<endl;
while(br<4)
{
br+=1;
string (newstar.size(br, '*') );
cout<<newstar<<endl;
}
return 0;
}
Now, that program resulted error because of string (newstar.size(br, '*') );
which I don't understand why is that wrong and why is string newstar(br, '*');
correct without.size and without ()?
The error is
prog.cc: In function 'int main()':
prog.cc:14:13: error: 'newstar' was not declared in this scope
string (newstar.size(br, '*') );
^~~~~~~
prog.cc:14:13: note: suggested alternative: 'star'
string (newstar.size(br, '*') );
^~~~~~~
star
Because you did not declare newstar
. The compiler already stops there, but there is more wrong: std::string::size
takes no paramters and it is not clear what you expect from writing string ( some_number);
.
As I dont really understand the logic of your code I cannot offer you a complete fix, but I can give a hint. This:
std::cout << std::string(4,'*');
constructs a std::string
consisting of 4 copies of the character *
and prints that on the console.
I think your intention was to have:
string newstar(br, '*');
istead of:
string (newstar.size(br, '*') );
also maybe increment br after that line, and you could remove 'cout << star << endl;'
See the fill constructor: http://www.cplusplus.com/reference/string/string/string/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.