I'm currently learning through Bjarne Stroustrup's book "Programming: Principles and Practice Using C++".
I'm at the point where we try to concatenate strings using the following example (edited for the actual code as requested):
I apologize I failed to mention that the program works. But whenever I type both names it shows blank.
#include "std_lib_facilities.h"
int main()
{
string first;
string second;
string name = first + ' ' + second;
cout << "Please enter your first and second names\n";
cin >> first >> second;
cout << "Hello, "<<name<<'\n';
}
I just want to mention that this is not the way it was written in the book. I just wanted to play with different setups such as putting all the string variables in one area together. However, I found out that String name = first + ' ' +second; does not work unless I put it after the cin >> first >> second; line.
Is there an explanation for this?
Reference code from the book:
int main ()
{
cout<<"Please enter your first and second name\n";
string first;
string second;
cin>>first>>second;
string name=first +' '+second;
cout<< Hello, "<<name<<'\n';
}
I mean it probably did work. The problem here is that the result isn't what you think it is.
Strings are usually empty by default. So an empty string + a space + another empty string = just a space. It's highly likely you're seeing this space, but it looks empty because spaces are, well, spaces.
If you want to concatenate the input from the user, you will have to do so after you capture that input as the program has no other way to know what the user inputted otherwise.
If you're still confused, I'm afraid I unfortunately don't know what else to tell you other than that's just the way C++ works.
I would suggest looking more into what a variable is and what cin does. A variable holds a value. cin retrieves input from a user and puts it into a variable. Of course adding two variables with no value will not work as if there were values there. Instead, you are adding two blank strings to a space.
Also, when you do:
string name=first +' '+second;
You are setting name to the value of first plus the value of ' ' plus the value of second. The variable is not a reference to those values. Meaning that changing first and second after this point does not affect the value of the 'name' variable.
Related
I managed to get this program to work. If the user types an unfixed amount of integers, the program will calculate the average value of it. But I need to end it with <Ctrl-D> in my terminal (end of file) in order for it to work. Why can I not just press enter for it to work?
I also believe that I've used an unnecessary amount of variables. Can it be narrowed down to maybe 2 variables?
#include <iomanip>
#include <iostream>
using namespace std;
int main ()
{
int digit {};
int res {};
int counter {};
cout << "Type in integers: ";
while (cin >> digit)
{
counter ++;
res += digit;
}
cout << "The mean was " << setw(1) << setprecision(1) << fixed << static_cast<double>(res) / static_cast<double>(counter) << endl;
return 0;
}
Why can I not just press enter for it to work?
Because that's not how the overloaded >> formatted extraction operator works. This operator skips over an unlimited amount of whitespace characters, including newline characters, until it reads the integer. It's simply how it works: it will read newlines and spaces, after newlines, and spaces, until it sees a digit. That's its mission in life: read and skip over spaces and newlines until it reads at least one digit. It never gets tired of reading newlines and spaces, and will keep going as long that's the case.
To handle input in the fashion you describe requires a completely different approach: using std::getline to read a single line of input into a std::string, up until the next newline character. Then, once that's done, you can check if the std::string is empty, which means that no input was entered, and then terminate; otherwise take the input in std::string and convert it to an int value (using std::stoi, std::from_chars, or a std::istringstream -- take your pick), and then proceed with the existing algorithm.
Can it be narrowed down to maybe 2 variables?
How do you expect to do that? Hard, immutable logic dictates that you must keep track of at least two discrete values: the total sum and the number of values read. But then you just ran out of variables. You have no more variables to use for storing the next read value (if there is one), using whatever approach you chose to use. So, you can't do it. Rules of logic require the use of at least three variables, possibly more depending on how fancy and robust you want your input validation to work.
The user inputs their full name into the console and gets stored in an array using getline(). The array that the name is stored in is of type "string"
The problem i am trying to solve is as follows:
Include a for-loop that counts the number of names in the full name
and then uses that information in a second for loop that displays the
full name formally.
So if the user enters in 'Paul Matthew Jones', I want the console to display 'PM Jones'.
There are a few restrictions for the question. I can't use any functions. I must use only 2 loops and I must only use 1 array.
for (int i = 0; i < myName.length(); i++)
{
if (myName[i] == ' ')
{
nameLength = nameLength + 1;
}
}
Split the input to individual strings in first place (e.g. using std::istringstream and a std::vector<std::string> to collect them).
Then just collect all of the first characters and concatenate these, besides for the last string in the split up strings collection which should be appended in whole, and prefixed with a ' ' character.
I'm a software engineering student, and i need some help with an assignment i was given
i need a code that corrects a sentence written inside out
example;
i love programming
rp evol i gnimmargo
(what i mean by inside out .... that the sentence gets cut into half and each half is flipped)
i need to correct the scrambled sentence
i already started it by counting the charterers in the string that the user enters and cutting the sentence .... but i just cant figure out how to flip each half then join them
any ideas??
#include <iostream>
#include <string>
using namespace std;
//prototype
int NumberOfChar(string testCase);
int main()
{
// declaration
int N, halfCharNum, halfTestCase, size;
string testCase;
// input
cout<<"please enter an integer number, that will represent the number of test cases: "<<endl;
//cin>>N;
cout<< NumberOfChar(testCase)<<endl;
halfCharNum=size/2;
return 0;
}
int NumberOfChar(string testCase)
{
cout << "Enter your string: " <<endl;
getline(cin,testCase);
const int size=testCase.length();
cout << "The total number of characters entered is: " << endl;
return size;
}
This takes all of two lines of C++ code.
1) reverse the string (std::reverse)
2) Rotate the string left n characters where n is half the number of characters in the string. (std::rotate)
First, replace each element in the string with the element on the other end and work your way in.
i.e. in the string "rp evol i gnimmargo" exchange the first character "r" with the last character "o" and then work your way in, next exchanging "p" with "g" and so on.
That leaves you with "ogramming i love pr"
Then, swap the first and second halves of the string.
i.e. "ogramming i love pr" can be split into "ogramming" and " i love pr" -- just swap them for " i love pr" and "ogramming" and combine them
Just use a large dictionary of english words and implement an evolutionary algorithm. Might not be the shortest path to glory but definitely a fun task :-)
Sample dictionaries (you might need anyway) can be found
here,
here,
or here
All:
I got one question in string parsing:
For now, if I have a string like "+12+400-500+2:+13-50-510+20-66+20:"
How can I do like calculate total sum of each segment( : can be consider as end of one segment). For now, what I can figure out is only use for to loop through and check +/- sign, but I do not think it is good for a Universal method to solve this kind of problem :(
For example, the first segment, +12+400-500+2 = -86, and the second segment is
+13-50-510+20-66+20 = -573
1) The number of operand is varied( but they are always integer)
2) The number of segment is varied
3) I need do it in C++ or C.
I do not really think it as a very simple question to most newbie, and also I will claim this is not a homework. :)
best,
Since the string ends in a colon, it is easy to use find and substr to separate out parts of the string partitioned by ':', like this:
string all("+12+400-500+2:+13-50-510+20-66+20:");
int pos = 0;
for (;;) {
int next = all.find(':', pos);
if (next == string::npos) break;
string expr(all.substr(pos, (next-pos)+1));
cout << expr << endl;
pos = next+1;
}
This splits the original string into parts
+12+400-500+2:
and
+13-50-510+20-66+20:
Since istreams take leading plus as well as leading minus, you can parse out the numbers using >> operator:
istringstream iss(expr);
while (iss) {
int n;
iss >> n;
cout << n << endl;
}
With these two parts in hand, you can easily total up the individual numbers, and produce the desired output. Here is a quick demo.
You need to seperate operands and operators. To do this you can use two queue data types one for operands and one for operators
split by :, then by +, then by -. translate into int and there you are.
Your expression language seems regular: you could use a regex library - like boost::regex - to match the numbers, the signs, and the segments in groups directly, with something like
((([+-])([0-9]+))+)(:((([+-])([0-9]))+))+
I just started c++ today. I am doing some simple registration program. I want to validate the input. I got stuck when validate fullname and birth_date. Here is my requirements:
Fullname: I just want to check if its empty and no punctuation
date_birth: i know this is abit tricky. But if I could validate if the input is valid like: month(1-12), date(1-30) and year (not more than current year) should be enough.
Any quick way to do this?
EDIT:
I tried googled string validation, i am still getting lots of errors. Here is my current code:
string fullname;
do{
cout << endl << "Please enter your fullname";
cin >> fullname;
} while(!ispunct(fullname));
My error message is:
XXXX: no matching function for call to `ispunct(std::string&)'
I already include the library, is this a correct way to check string input. How do you usually do the validation?
EDIT 2:
bool valid;
string fullname;
do{
valid = true;
cout << endl << "Please enter your fullname";
cin >> fullname;
string::iterator it;
for ( it=fullname.begin() ; it < fullname.end(); it++ )
if(ispunct(*it)){
valid = false;
}
} while(!ispunct(fullname));
Its weird, I entered: "!!!", it still by pass. Something is wrong in my code?
Well, I'll try to steer you in the right direction. Firstly, in order to validate the string, you'll need to iterate over it character by character. You can do this using iterators and a for loop. The string class has a begin() and end() method, which you can use to loop over the whole string and examine each character.
Once you're looping over the string, all you need to do is write code to validate it based on your requirements. To make sure there's no punctuation characters, you can use the std::ispunct function, which will tell you whether or not a character is a punctuation character. If you find any punctuation characters, simply consider it an error.
Your first requirement, checking whether the string is empty, is trivial. The string class has an empty() method which returns true if the string is empty.
Validating the birthday is more tricky. This is the sort of thing regular expressions were made for. Unfortunately, C++ has no built-in support for regular expressions (at least not until the next version of the standard). If you're interested, Boost has a good regular expression library in the meantime.
Otherwise, you'll need to loop over the string and validate each character. Make sure the string starts with characters that form a word corresponding to a month name, then make sure a parenthesis falls after that, etc. You'll need to decide how to handle white spaces in between characters. This will be tricky, but it's a good practice exercise to become familiar with C++.
Solution for the second requirement can be trivial if you choose different data type to represent date of birth. Constraints you mentioned here are all numeric (1<= day <= 31, 1 <= month <= 12, 1900 <= year <=2010) and date of birth is basically a set of three numbers so consider using struct type for birth_date variable, something like this:
struct Date{
unsigned int day;
unsigned int month;
unsigned int year;
};
Date birth_date = {3, 12, 1983};
When you pass birth_date to function that performs validation, you just need to compare struct members against limits.