new to programming here. I'm confused as to how I'm supposed to use "isalpha" to figure this out. I have no clue how to start it.
A 2-character string, passCode, is read from input. Replace each alphabetic character in passCode with '&'. Otherwise, passCode is not changed.
Ex: If the input is c4, then the output is:
&4
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string passCode;
getline(cin, passCode);
cout << passCode << endl;
return 0;
}
In many many programming languages, so called loops are used to execute or repeat blocks of code.
Or do iterate over "something". Therefore loops are also called Iteration statements
Also C++ has loops or iteration statements. The basic loop constructs are
for loops,
while loops,
do-while loops
Range-based for loops
Please click on the links and read the descriptions in the C++ reference. You can use any of them to solve your problem.
Additionally, you need to know that a string is a container. Container means that a varibale of such a type contains other elements from nearly any type.
A string for example, contains characters.
Example: If you have a string equivalent to "Hello", then it contains the characters 'h', 'e', 'l', 'l', 'o'.
Another nice property of some containers is, that they have an index operator or better said, a subscript operator []. So, if you want to access a charcter in your string, you may simply use your variable name with an index specified in the subscript operator.
Very important: Indices in C++ start with 0. So the first character in a string is at index 0. Example:
std::string test = "Hello";
std::cout << test[0];
will print H
With all the above gained know how, we can now solve your problem easily. We will iterate over all characters in your string, and then check, if a character is an alphabetic charcter. In that case, we will replace it.
One of many many possible implementations:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string passCode;
getline(cin, passCode);
for (unsigned int i = 0; i < passCode.length(); ++i) {
if (isalpha(passCode[i])) {
passCode[i] = '&';
}
}
cout << passCode << endl;
return 0;
}
I believe this is what you're looking for when using isalpha.
Looking at the 2 character input for passCode, check each place (0 and 1) if it is a an alpha and change it to &.
if (isalpha(passCode.at(0)) {
passCode.at(0) = '&';
}
if (isalpha(passCode.(1)) {
passCode.at(1) = '&';
}
Related
I was trying to print the last character of a string, for example str[]="This is an example", I tried to print the 'e' of "example" with some functions, but none of them funct as I expected. I know it's more simple to write in the code the position number of the last character, but as in strrchr function, the code work by itself. Is there a function that works similar?
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
int main ()
{
char str[] = "This is an example";
char * pch;
pch=strrchr(str,'s');
cout<<str<<endl;
cout<<"Last time 's' was found was in position: "<<pch-str+1<<endl;
cout<<"Last character in this example is "<<str[X];
return 0;
}
From the documentation for strrchr:
The terminating null-character is considered part of the C string. Therefore, it can also be located to retrieve a pointer to the end of a string.
Thus, strrchr(str, '\0')[-1] will have the last character. Note that this is only safe if you're sure str isn't empty.
Simple: use the standard strlen function, as follows:
int main ()
{
char str[] = "This is an example";
char * pch;
pch=strrchr(str,'s');
cout<<str<<endl;
cout<<"Last time 's' was found was in position: "<<pch-str+1<<endl;
size_t X = strlen(str) - 1; // X will be the index of the last character!
cout<<"Last character in this example is "<<str[X];
return 0;
}
Or, just for fun, if you want to handle the case where the string could be empty:
size_t X = strlen(str); X -= !!X; // Non-zero: decrement, Zero: Leave as is
cout<<"Last character in this example is "<<str[X];
Then, for an empty string, cout << str[X] will show whatever the implementation does for a NULL character.
If you don't mind to use std::string this snippet would do the job.
#include <string>
#include <iostream>
int main() {
std::string str = "This is some text";
std::cout << str.back() << std::endl;
}
I assume you choose char[] to avoid allocation or something similar so am not going to discuss std::string as an option.
Three solutions, one in modern C++ using string_view, one using templates ;
and one using std::size and the index operator.
Solution 1.1:
I recommend you use this, its nearly optimal and is much more readable than the alternative. It also doesn't require as much boiler plate to handle empty strings, or strings without null termination.
#include <string_view>
#include <iostream>
int main()
{
std::string_view str = "This is an example";
auto X = str.find_last_of('s');
//
// Make sure the character exists in the string
if (X != std::string_view::npos)
{
std::cout<< str << std::endl;
std::cout<< "Last time 's' was found was in position: " << X << std::endl;
}
else
{
std::cout<<"Character did not exist in string.\n";
}
if (!str.empty()) std::cout<< "Last character in this example is " << str.back();
else std::cout << "Cannot get the last character in an empty string!";
return 0;
}
You can run the solution here:
https://onlinegdb.com/SJK2hjPEB
The same code will work with std::string.
Solution 1.2
This is a compile time only solution, it relies on the string being aggregate constructed or constructed as a string.
template <size_t N>
constexpr char LastCharacter(char (&input)[N])
{
static_assert(N >= 1, "A character array representing a string must have atleast 1 character AND a null terminator.");
return (input[N - 1] == '\0') ? input[N - 2] : input[N - 1];
}
Tests and examples shown here:
https://onlinegdb.com/HJ_IXEd4H
Solution 2
This has the required checks to avoid issues with empty strings.
In this version it is a compile time error to have an empty array. str[] = "" is not an empty array it has 1 character, a null. An empty string has no last character, this needs to be handled. It also should be handled for the strrchr.
If you must use strrchr(...) then consider checking whether the result is nullptr. If a nullptr is returned then the character wasn't found in the string:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <cassert>
using namespace std;
int main ()
{
char str[] = {'h', 'e','l', 'l', 'o', '\0'};
//
// Prevent use with an empty array (1 character + 1 null character minimum)
if (std::size(str) > 1)
{
//
// Only allow null terminated strings.
assert( str[std::size(str) - 1] == '\0' );
//
// There skip the last null character and get the last character
// No null character, not compensation needed
cout<<"Last character in this example is "<< str[ std::size(str) - 2 ];
}
else
{
cout << "Cannot process empty string\n";
}
return 0;
}
https://onlinegdb.com/SkrP2Q_NB
Please note, defining strings as arrays enables strings to exist without null terminators. In that case the above solution does not function. If you want to handle that case you need to check for the existance of a null terminator and if it is present compensate in code. assert causes an error if there isn't a null terminator.
--
To elaborate on the problem with strrchr. The function requires a null terminated string.
The terminating null-character is considered part of the C string.
Therefore, it can also be located to retrieve a pointer to the end of
a string.
http://www.cplusplus.com/reference/cstring/strrchr/
This was quoted by the previous answer, but for completeness also here.
The datatype you are using allows a character array with no null termination:
char data[] = {'a', 'b', 'c'};
That is what the assert handles in the solution 2.
I was given a code from my professor that takes multiple lines of input. I am currently changing the code for our current assignment and I came across an issue. The code is meant to take strings of input and separate them into sentences from periods and put those strings into a vector.
vector<string> words;
string getInput() {
string s = ""; // string to return
bool cont = true; // loop control.. continue is true
while (cont){ // while continue
string l; // string to hold a line
cin >> l; // get line
char lastChar = l.at(l.size()-1);
if(lastChar=='.') {
l = l.substr(0, l.size()-1);
if(l.size()>0){
words.push_back(s);
s = "";
}
}
if (lastChar==';') { // use ';' to stop input
l = l.substr(0, l.size()-1);
if (l.size()>0)
s = s + " " + l;
cont = false; // set loop control to stop
}
else
s = s + " " + l; // add line to string to return
// add a blank space to prevent
// making a new word from last
// word in string and first word
// in line
}
return s;
}
int main()
{
cout << "Input something: ";
string s = getInput();
cout << "Your input: " << s << "\n" << endl;
for(int i=0; i<words.size(); i++){
cout << words[i] << "\n";
}
}
The code puts strings into a vector but takes the last word of the sentence and attaches it to the next string and I cannot seem to understand why.
This line
s = s + " " + l;
will always execute, except for the end of input, even if the last character is '.'. You are most likely missing an else between the two if-s.
You have:
string l; // string to hold a line
cin >> l; // get line
The last line does not read a line unless the entire line has non-white space characters. To read a line of text, use:
std::getline(std::cin, l);
It's hard telling whether that is tripping your code up since you haven't posted any sample input.
I would at least consider doing this job somewhat differently. Right now, you're reading a word at a time, then putting the words back together until you get to a period.
One possible alternative would be to use std::getline to read input until you get to a period, and put the whole string into the vector at once. Code to do the job this way could look something like this:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <iterator>
int main() {
std::vector<std::string> s;
std::string temp;
while (std::getline(std::cin, temp, '.'))
s.push_back(temp);
std::transform(s.begin(), s.end(),
std::ostream_iterator<std::string>(std::cout, ".\n"),
[](std::string const &s) { return s.substr(s.find_first_not_of(" \t\n")); });
}
This does behave differently in one circumstance--if you have a period somewhere other than at the end of a word, the original code will ignore that period (won't treat it as the end of a sentence) but this will. The obvious place this would make a difference would be if the input contained a number with a decimal point (e.g., 1.234), which this would break at the decimal point, so it would treat the 1 as the end of one sentence, and the 234 as the beginning of another. If, however, you don't need to deal with that type of input, this can simplify the code considerably.
If the sentences might contain decimal points, then I'd probably write the code more like this:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <iterator>
class sentence {
std::string data;
public:
friend std::istream &operator>>(std::istream &is, sentence &s) {
std::string temp, word;
while (is >> word) {
temp += word + ' ';
if (word.back() == '.')
break;
}
s.data = temp;
return is;
}
operator std::string() const { return data; }
};
int main() {
std::copy(std::istream_iterator<sentence>(std::cin),
std::istream_iterator<sentence>(),
std::ostream_iterator<std::string>(std::cout, "\n"));
}
Although somewhat longer and more complex, at least to me it still seems (considerably) simpler than the code in the question. I guess it's different in one way--it detects the end of the input by...detecting the end of the input, rather than depending on the input to contain a special delimiter to mark the end of the input. If you're running it interactively, you'll typically need to use a special key combination to signal the end of input (e.g., Ctrl+D on Linux/Unix, or F6 on Windows).
In any case, it's probably worth considering a fundamental difference between this code and the code in the question: this defines a sentence as a type, where the original code just leaves everything as strings, and manipulates strings. This defines an operator>> for a sentence, that reads a sentence from a stream as we want it read. This gives us a type we can manipulate as an object. Since it's like a string in other ways, we provide a conversion to string so once you're done reading one from a stream, you can just treat it as a string. Having done that, we can (for example) use a standard algorithm to read sentences from standard input, and write them to standard output, with a new-line after each to separate them.
I got a string and I want to remove all the punctuations from it. How do I do that? I did some research and found that people use the ispunct() function (I tried that), but I cant seem to get it to work in my code. Anyone got any ideas?
#include <string>
int main() {
string text = "this. is my string. it's here."
if (ispunct(text))
text.erase();
return 0;
}
Using algorithm remove_copy_if :-
string text,result;
std::remove_copy_if(text.begin(), text.end(),
std::back_inserter(result), //Store output
std::ptr_fun<int, int>(&std::ispunct)
);
POW already has a good answer if you need the result as a new string. This answer is how to handle it if you want an in-place update.
The first part of the recipe is std::remove_if, which can remove the punctuation efficiently, packing all the non-punctuation as it goes.
std::remove_if (text.begin (), text.end (), ispunct)
Unfortunately, std::remove_if doesn't shrink the string to the new size. It can't because it has no access to the container itself. Therefore, there's junk characters left in the string after the packed result.
To handle this, std::remove_if returns an iterator that indicates the part of the string that's still needed. This can be used with strings erase method, leading to the following idiom...
text.erase (std::remove_if (text.begin (), text.end (), ispunct), text.end ());
I call this an idiom because it's a common technique that works in many situations. Other types than string provide suitable erase methods, and std::remove (and probably some other algorithm library functions I've forgotten for the moment) take this approach of closing the gaps for items they remove, but leaving the container-resizing to the caller.
#include <string>
#include <iostream>
#include <cctype>
int main() {
std::string text = "this. is my string. it's here.";
for (int i = 0, len = text.size(); i < len; i++)
{
if (ispunct(text[i]))
{
text.erase(i--, 1);
len = text.size();
}
}
std::cout << text;
return 0;
}
Output
this is my string its here
When you delete a character, the size of the string changes. It has to be updated whenever deletion occurs. And, you deleted the current character, so the next character becomes the current character. If you don't decrement the loop counter, the character next to the punctuation character will not be checked.
ispunct takes a char value not a string.
you can do like
for (auto c : string)
if (ispunct(c)) text.erase(text.find_first_of(c));
This will work but it is a slow algorithm.
Pretty good answer by Steve314.
I would like to add a small change :
text.erase (std::remove_if (text.begin (), text.end (), ::ispunct), text.end ());
Adding the :: before the function ispunct takes care of overloading .
The problem here is that ispunct() takes one argument being a character, while you are trying to send a string. You should loop over the elements of the string and erase each character if it is a punctuation like here:
for(size_t i = 0; i<text.length(); ++i)
if(ispunct(text[i]))
text.erase(i--, 1);
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string str = "this. is my string. it's here.";
transform(str.begin(), str.end(), str.begin(), [](char ch)
{
if( ispunct(ch) )
return '\0';
return ch;
});
}
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;//string is defined here.
cout << "Please enter a string with punctuation's: " << endl;//Asking for users input
getline(cin, s);//reads in a single string one line at a time
/* ERROR Check: The loop didn't run at first because a semi-colon was placed at the end
of the statement. Remember not to add it for loops. */
for(auto &c : s) //loop checks every character
{
if (ispunct(c)) //to see if its a punctuation
{
c=' '; //if so it replaces it with a blank space.(delete)
}
}
cout << s << endl;
system("pause");
return 0;
}
Another way you could do this would be as follows:
#include <ctype.h> //needed for ispunct()
string onlyLetters(string str){
string retStr = "";
for(int i = 0; i < str.length(); i++){
if(!ispunct(str[i])){
retStr += str[i];
}
}
return retStr;
This ends up creating a new string instead of actually erasing the characters from the old string, but it is a little easier to wrap your head around than using some of the more complex built in functions.
I tried to apply #Steve314's answer but couldn't get it to work until I came across this note here on cppreference.com:
Notes
Like all other functions from <cctype>, the behavior of std::ispunct
is undefined if the argument's value is neither representable as
unsigned char nor equal to EOF. To use these functions safely with
plain chars (or signed chars), the argument should first be converted
to unsigned char.
By studying the example it provides, I am able to make it work like this:
#include <string>
#include <iostream>
#include <cctype>
#include <algorithm>
int main()
{
std::string text = "this. is my string. it's here.";
std::string result;
text.erase(std::remove_if(text.begin(),
text.end(),
[](unsigned char c) { return std::ispunct(c); }),
text.end());
std::cout << text << std::endl;
}
Try to use this one, it will remove all the punctuation on the string in the text file oky.
str.erase(remove_if(str.begin(), str.end(), ::ispunct), str.end());
please reply if helpful
i got it.
size_t found = text.find('.');
text.erase(found, 1);
I'm looking for a way to store a large input, character by character in an array.
For example think user types 324354545434erdfdrr.........6677. For the first part I need to have its length, (think I only wants to count its alphabets not numbers) then I want to create an array based on its length (number of its alphabets), (a[length]), then I need to store the input, character by character in the array.
What situation you will decide me?
I'm thinking about using
getch();
function but don't know how to start.
Why not use string in c++?
#include <string>
#include <iostream>
int main(void)
{
std::string str;
std::cin >> str;
std::cout << str << std::endl;
return 0;
}
I have an integer 1 and i want to display it as a character '1' in C++. So far I have only managed to convert it from say integer 65 to character 'A'.
How do you stop this ?
int theDigit = 1;
char ch = theDigit+'0';
This works because it's guaranteed1 that the sequence of characters '0'...'9' is contiguous, so if you add your number to '0' you get the corresponding character. Obviously this works only for single digits (if theDigit is e.g. 20 you'll get an unrelated character), if you need to convert to a string a whole number you'll need snprintf (in C) or string streams (in C++).
C++11, [lex.charset] ΒΆ3:
In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.
By the way, I suppose that they didn't mandate contiguity also in the alphabetical characters just because of EBCDIC.
Use the stringstream.
int blah = 356;
stringstream ss;
string text;
ss << blah;
ss >> text;
Now text contains "356"(without quotes). Make sure to include the header files and use the namespace if you are going to copy my code:
#include <sstream> //For stringstream
#include <string>
using namespace std;
#include <stdio.h>
#include <stdlib.h>
int i = 3;
char buffer [25];
itoa (i, buffer, 10);
printf ("Integer: %s\n",buffer);
Integer: 3
You did just ask about printing an integer, so the really simple c++ answer is:
#include <iostream>
int main()
{
int value = 1;
std::cout << value << endl;
return 0;
}