Reputation: 1
I want to print characters, numbers, and special characters one by one below each other, but having an error in taking string.
#include<iostream.h>
#include<string.h>
main()
{
string s = "124#$&afhj";
int i;
for(i=0;i<s.length();i++)
{
if((s[i]>=65&&91>=s[i])||(s[i]>=95&&123>=s[i]))
{
cout<<s[i]<<endl;
}
else
{
if(s[i]>=0&&s[i]<=9)
{
cout<<s[i]<<endl;
}
else
{
cout<<s[i];
}
}
}
}
Upvotes: 0
Views: 2306
Reputation: 27538
<iostream.h>
. It must be <iostream>
. You aren't using an ancient compiler from the 1990s, are you? There are excellent free and modern C++ compilers available for Windows and Linux. Download one and use it.<string.h>
exists but is not the correct header to get std::string
; it instead contains C-style char*
functions and is not what you want here.main
must return int
, even though a return 0
statement is not necessary.string
, cout
or endl
without the std::
prefix. So make it std::string
, std::cout
and std::endl
. Do not use using namespace std
.std::endl
but '\n'
.'A'
instead. And of course, your >=
comparisons are not guaranteed to work. Getting this right is surprisingly difficult in C++. You can use std::isalpha
but must pay attention not to invoke undefined behaviour. See also a more detailed treatise on this subject.>=
comparisons.i
outside of the loop? It needlessly increases its scope. And it has the wrong type; it's a signed int when it should be an unsigned one, or simply std::string::size_type
. However, you should consider using a range-based for loop to iterate through the string anyway.'0'
and '9'
. Note how in this case, C++ does guarantee consecutive values for the characters even if ASCII is not guaranteed. You can therefore use range comparisons safely.Here we go:
#include <iostream>
#include <string>
#include <cctype>
int main()
{
std::string s = "124#$&afhj";
for (auto&& character : s)
{
if (std::isalpha(static_cast<unsigned char>(character)))
{
std::cout << character << '\n';
}
else
{
if (character >= '0' && character <= '9')
{
std::cout << character << '\n';
}
else
{
std::cout << character;
}
}
}
}
This will work. I don't think it's really useful, because what it does is:
But after all, that's what the original program's intention was.
Upvotes: 2
Reputation: 79
In your code is many mistakes. In my opinion your code should look like:
#include<iostream>
#include<string>
using namespace std;
int main() {
string s = "124#$&afhj";
unsigned int i;
for (i = 0; i < s.length(); i++) {
if ((s[i] >= 65 && 91 >= s[i]) || (s[i] >= 95 && 123 >= s[i])) {
cout << s[i] << endl;
} else {
if (s[i] >= 0 && s[i] <= 9) {
cout << s[i] << endl;
} else {
cout << s[i];
}
}
}
}
Upvotes: -1