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 () ?
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 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.
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;
//...
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;
}
This question already has answers here:
Printing variable in quotation marks C++
(4 answers)
how to declare char * with input of {"data": "0001"}'
(1 answer)
Closed 4 years ago.
I am beginning my C++ coding with challenges from the book Exercises for Programmers by Brian P.Hogan. I am capable of doing this, it's just I have never come across this int he 4 weeks I have been coding.
I am attempting to write a simple program that prompts the user for a quote, and the author of the quote.
Code:
#include <iostream>
#include <cstring>
int main(int argc, char const *argv[])
{
std::string quote;
std::string author;
std::cout << "Please enter a quote" << '\n';
std::cin >> quote;
std::cout << "Please enter the author" << '\n';
std::cin >> author;
std::cout << author << " said " << ""quote"" << '\n';
return 0;
}
Output:
compile error
With the above code, it compiles wrong. This is because of the double quotation marks
std::cout << author << " said " << ""quote"" << '\n';
The desired output will look something like this
What is the quote? These aren't the droids you're looking for.
Who said it? Obi-Wan Kenobi
Obi-Wan Kenobi says, "These aren't the droids
you're looking for."
Notice the quotation marks on the desired output around the quote (how a quote should really look anyway). I have looked online, but haven't been able to find a solution specifically for C++.
What I am asking, is how do i display text in the terminal with quotation marks around it. (Like this - "hello")
I hope you understand the question. It is my first post and I tried to make it as clear as possible what the issue is.
Thanks in advance.
escape the quote:
https://ideone.com/lcrYlA
#include <iostream>
int main()
{
// your code goes here
std::cout << " hello " << " \"world\"" << std::endl;
return 0;
}
You can of course do:
std::cout << author << " said \" "<< quote << "\"\n";
Quote the quote with \
std::cout << "the character \" is a quote";
You can escape the string using a backslash \" e.g printf("Quotes \"\" ");
I am having trouble with recalling the name of a person that was previously entered into the program with a cout statement.
int main()
{
string donorName;
string donorGender;
int donorWeight;
int donorHeight;
int donorAge;
cout << "What is the donor's name?" << endl;
getline(cin, donorName);
if (donorAge < 16)
{
cout << "--- No, **(name)** you cannot donate blood" << endl;
}
Can you help me how I can put "No, "donor Name" you can not donate blood into the cout statement from the name they put in for donor name?
Thank you so much.
You are probably looking for string interpolation like for example in PHP or in TypeScript, where you can conveniently write:
const my_variable = 123;
const text = `some text ... ${my_variable} ...`;
Unfortunately, C++ doesn't have such a feature. There has been a proposal for it, but I don't think it ever got anywhere.
If the goal is just to print the text, then the safest and easiest way to do so is to split the literal into two parts and print them separately, along with the variable in between:
std::cout << "--- No, " << donorName << ", you cannot donate blood\n";
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
So, I started using C++ today, and wanted to make a small, text-based adventure, but that didn't turn out all that well.
Here's my code:
string answer;
string name;
string charName;
std::cout << "<Ominous voice> Hi there, what's your name?" << std::endl;
std::cout << "Enter your name:" << std::endl;
getline(cin, name);
std::cout << "<Ominous voice> " << name << "? That's an... interesting name." << std::endl;
std::cin.ignore();
std::cout << "<Ominous voice> Before we start off... You need to learn the basics, so let's break the fourth wall shall we?" << std::endl;
std::cin.ignore();
std::cout << "<Ominous voice> I'm here to guide you on this wonderfull adventure... for just $ 9.99." << std::endl;
std::cin.ignore();
std::cout << "<Ominous voice> You can name me everything you want, since I'm a fragment of your imagination anyway... So, what about it?" << std::endl;
std::cout << "Enter a name:" << std::endl;
getline(cin, charName);
strcpy (str1,"<");
strcpy (str2,">");
strcat (str1,charName, 1);
strcat (charName,str2, charName.size();
std::cout << charName << " Well then, it seems I'm now called '" << charName << "' not sure if I like that." << std::endl;
std::cin.ignore();
std::cout << "This line does not show up" << std::endl;
Now I have 2 problems:
I get these messages when I start the program:
/home/ubuntu/workspace/hello-cpp-world.cc: In function ‘int main()’:
/home/ubuntu/workspace/hello-cpp-world.cc:23:13: error: ‘str1’ was not declared in this scope
strcpy (str1,"<");
^
/home/ubuntu/workspace/hello-cpp-world.cc:24:13: error: ‘str2’ was not declared in this scope
strcpy (str2,">");
^
/home/ubuntu/workspace/hello-cpp-world.cc:26:43: error: expected ‘)’ before ‘;’ token
strcat (charName,str2, charName.size();
^
That last line, saying "This line does not show up", actually doesn't show up.
I know I'm basic and this is probably not the most efficient way to do this, but I'm a beginner.
You have to declare string str1 before using it. Decraling means
std::string str1;
In C++ the definition is e.g.
str1 = "heureka";
And the declaration has always be in front of the definition.
But you can do both in one line:
std::string str1 = "heureka";
or
std::string str1("heureka");
If you want to add "<" in front and ">" behind the characters name. You can do it as follows:
charName = "<" + charName + ">";
There is no need to create new strings for it. There is simply a + operator for strings and it is easier to use than strcpy, strcat or so.
The issue is that you haven't declared the strings str1 and str2.