I am trying to write a function that counts the number of characters in a string excluding spaces. However, the output is always wrong so there is something wrong with my code.
There is something wrong with my code but I can't figure it out. Please help me with my programming homework.
#include <iostream>
#include <bits/stdc++.h>
#include <stdio.h>
#include <ctype.h>
using namespace std;
int countLetters (char s[], int size_s){
int isLetter = 0;
for(int i =0; i<size_s;i++){
if (isalpha(s[i])){
isLetter ++;
}
}
return isLetter;
}
int main (){
char s[100];
gets(s);
int n = sizeof(s)/sizeof(s[0]);
cout << countLetters(s,n);
}
Here is an example of the wrong output:
hi
10
PS C:\Users\user\OneDrive\Desktop\cpp practical> cd "c:\Users\user\OneDrive\Desktop\cpp practical\" ; if ($?)
{ g++ count_letters.cpp -o count_letters } ; if ($?) { .\count_letters }
hi
6
PS C:\Users\user\OneDrive\Desktop\cpp practical> cd "c:\Users\user\OneDrive\Desktop\cpp practical\" ; if ($?)
{ g++ count_letters.cpp -o count_letters } ; if ($?) { .\count_letters }
hi
10
PS C:\Users\user\OneDrive\Desktop\cpp practical>
To begin with, I think your information source, like PepijnKramer, said in the comments, is a bit old. There are much easier data types you can use to complete this problem like std::string below.
First of all, your code is redundant in its header files: #include <bits/stdc++.h> is a nonstandard header, and you already have all the libraries you need.
Secondly, your main problem comes from the lines
char s[100];
gets(s);
int n = sizeof(s)/sizeof(s[0]);
You see, you first create a char array called s with 100 elements. However, you never give them an initial value, so the random garbage that came with the initialization stays. However, C++ also does not reset the values, so some of them may be randomized into letters. Then, you just use gets() to input the string. However, gets() only fills the array s with the number of characters you entered. Therefore, if you do not enter 100 characters, the random garbage that still can be a letter remains. Finally, when you do the size with the integer n, it turns out the result is always 100 because you defined s to have 100 elements, so when you run the function, you still iterate over the garbage in the array s. Therefore, depending on chance of what the garbage includes, your output is incorrect. To solve this, you can either you make sure to initialize it by
char s[100] = { };
Or switch a datatype. Here is a correct solution using std::string:
#include <bits/stdc++.h>
using namespace std;
int countLetters (string a, int size_s){
int isLetter = 0;
for (int i = 0; i < size_s; i++) {
if (isalpha(a[i])){
isLetter++;
}
}
return isLetter;
}
int main () {
string s;
getline(cin, s);
cout << countLetters(s, s.length());
}
Related
I am very new to coding, and have been practicing with some easy problems at codeforces.com. I was working on this problem, but it seemed to be asking for the input (all at once) yielding the output (all at once). I can only figure out how to get one output at a time.
Here are the basic instructions for the problem:
Input
The first line contains an integer n (1 ≤ n ≤ 100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.
Output
Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data.
Examples
input
4
word
localization
internationalization
pneumonoultramicroscopicsilicovolcanoconiosis
output
word
l10n
i18n
p43s
Here is my code:
#include <iostream>
#include <string>
using namespace std;
void wordToNumbers(string word){
int midLetters = word.length();
char firstLetter = word.front();
char lastLetter = word.back();
cout <<firstLetter <<(midLetters-2) <<lastLetter <<endl;
}
int main(){
string wordInput;
string firstNum;
getline(cin,firstNum);
int i = stoi(firstNum);
for(i>=1; i--;){
getline(cin,wordInput);
if (wordInput.length() > 10){
wordToNumbers(wordInput);
} else {
cout <<wordInput <<endl;
}
}
return 0;
}
it's perfectly fine to read and print output for the lines one by one.
Exactly your solution accepted: http://codeforces.com/contest/71/submission/16659519
I'm also a beginner in c++. My idea would be to save every line first in a buffer and then write everything to std::cout.
I use a std::vector as the buffer, cause IMO it is simple to understand and very useful in many cases. Basically it is a better array. You can read more about std::vector here.
#include <iostream>
#include <string>
//for use of std::vector container
#include <vector>
using namespace std;
void wordToNumbers(string word){
int midLetters = word.length();
char firstLetter = word.front();
char lastLetter = word.back();
cout <<firstLetter <<(midLetters-2) <<lastLetter <<endl;
}
int main(){
string wordInput;
string firstNum;
//container for buffering all our strings
vector<string> bufferStrings;
getline(cin,firstNum);
int i = stoi(firstNum);
//read line by line and save every line in our buffer-container
for(i>=1; i--;){
getline(cin,wordInput);
//append the new string to our buffer
bufferStrings.push_back(wordInput);
}
//now iterate through the buffer and write everything to cout
for(int index = 0; index < bufferStrings.size(); ++index) {
if (bufferStrings[index].length() > 10){
wordToNumbers(bufferStrings[index]);
} else {
cout <<bufferStrings[index] <<endl;
}
}
return 0;
}
Probably this is not the best or most beautiful solution, but it should be easy to understand :)
i'm newcomer.
i need size of input.
#include <iostream>
using namespace std;
int main()
{
int a,b,n;
char c[100];
cout<<"insert number of adjective : " ;
cin>>a;
for(b=0;b<a;b++)
{
cin>>c;
int length = sizeof(c);
cout<<length<<endl;
cout<<c<<endl;
}
return 0;
}
please help me for find the size lenght c
hamed
First off, never (as in really never) use std::cin >> array; wher e array is a char array (or a pointer to the start of such an arry) unless you have first set up the maximum amount of data which can be read by setting the stream's width(). Any teacher showing you how to use std::cin >> array; without advising to use width() has to be corrected!
You can, e.g., use
#include <cstring> // NOT <string>...
// ...
char c[100];
std::cin.width(sizeof(c));
if (std::cin >> c) {
std::size_t n = std::strlen(c);
// ...
}
to limit the number of character to be read to sizeof(c) - 1 (the -1 is there because a terminating null character is also read). Once you have successfully read your input (you also need to always check that input was actually successful) you can use strlen(c) to determine the number of characters read.
Personally, I read very rarely formatted data into a char array in real code. I normally simply read a std::string which is much easier and safer to use. I'd consider dealing with input to built-in array a somewhat more advanced topic.
you can use vector
#include <vector> ...
int n;
cin >> n;
vector<int> vec(n);
...
int size_of_vector = vec.size();
...
#include <string>
using namespace std;
int main()
{
////////////////////input
int a,b,n,i;
char c[100];
cout<<"insert number of adjective : " ;
cin>>a;
for(b=0;b<a;b++)
{
cin>>c;
n = strlen(c) ;
cout<<n<<endl;
/////////////////////////processing
if(c[n]=='r')
{
cout<<"ok";
}
/////////////////////////output
cout<<c<<endl;
}
}
This map help then.
/* strlen example */
#include <stdio.h>
#include <string.h>
int main ()
{
char szInput[256];
printf ("Enter a sentence: ");
gets (szInput);
printf ("The sentence entered is %u characters long.\n",(unsigned)strlen(szInput));
return 0;
}
first use: #include <string>
second write: int length = strlen(c); // insted of int length = sizeof(c);
strlen() function find length of string but you must include string library.
So i have a hw problem for my class where i have to store ten names, capitalize them and then sort them alphabetically. We just started using strings and there are some things that are still a little confusing to me. This code can store all the names in a string array, but the UpperCase seems to not be working. I dont know for sure but i think it is because I have second for loop running cap amount of times, which would be 10. And since not every string will have 10 elements, i'm running into problems?..Is that it or is it something else? Well i tried to fix this by using the .length (function?), to find the length of each name in the array, but I always get errors. Any help is appreciated, thanks!
#include<iostream>
#include<string>
using namespace std;
void UpperCase(string names[],int cap);
void print(string names[],int cap);
void swap(string names[],int &x,int &y);
string names[10];
int main(){
char a;
cout<<sizeof(a);
for(int i=0;i<10;i++){
cout<<"Enter a name for student "<<i+1<<" : ";
cin>>names[i];
cout<<endl;
}
UpperCase(names,10);
cout<<endl;
print(names,10);
cout<<endl;
print(names,10);
return 0;
}
void print(string names[],int cap){
for(int i=0;i<cap;i++)
cout<<names[i]<<endl;
}
void UpperCase(string names[],int cap){
for(int student=0;student<cap;student++){
for(int letter=0;letter<names[student].length();letter++){
if(names[student][letter]>='a')
names[student][letter]-=('a'-'A');
}
}
}
Your inner loop should be iterating for the length of the string. string::length() is a function, not a field, so you need the parentheses. There's also a standard library function for converting a character to upper case.
#include <cctype>
using std::toupper;
void UpperCase(string names[],int cap){
for(int student=0;student<cap;student++){
for(int letter=0;letter<names[student].length();letter++){
names[student][letter] = toupper(names[student][letter]);
}
}
}
..., but the UpperCase seems to not be working
So write a minimal program that just calls UpperCase on known input. It makes it easy to debug, and would also make a much better question. We don't need to see the print or swap to help with that, and prompting the user for input isn't relevant to whether UpperCase works or not.
Having said that, you should use std::string::length() - however, you say
Well i tried to fix this by using the .length (function?), to find the length of each name in the array, but I always get errors
but don't show what you actually tried, or what the errors were.
Here's a minimal, complete and self-contained program, using std::toupper as per T.C.'s answer. I changed it to demonstrate more modern style, and to show there are easier ways to confirm your functions work than to write a whole program and then find out it's broken.
#include <algorithm> // for transform, for_each
#include <cctype> // for toupper
#include <string>
#include <vector> // easier to use (correctly) than bare arrays
// change a string to upper case
void str_toupper(std::string &s) {
std::transform(s.begin(), s.end(),
s.begin(),
[](char c) -> char { return std::toupper(c); });
}
// change a vector of strings to upper case
void vec_toupper(std::vector<std::string>& v) {
std::for_each(v.begin(), v.end(), str_toupper);
}
using namespace std;
int main() {
vector<string> const input = { "bob", "alice cooper", "Eve" };
vector<string> const expected = { "BOB", "ALICE COOPER", "EVE" };
vector<string> working = input;
vec_toupper(working);
return working == expected ? 0 : -1;
// use cout or debugger to solve problem only if program returns nonzero
}
Is there anyway , if I enter any string , then I want to scan ASCII value of each character inside that string , if I enter "john" then I should get 4 variables getting ASCII value of each character, in C or C++
Given a string in C:
char s[] = "john";
or in C++:
std::string s = "john";
s[0] gives the numeric value of the first character, s[1] the second an so on.
If your computer uses an ASCII representation of characters (which it does, unless it's something very unusual), then these values are the ASCII codes. You can display these values numerically:
printf("%d", s[0]); // in C
std::cout << static_cast<int>(s[0]); // in C++
Being an integer type (char), you can also assign these values to variables and perform arithmetic on them, if that's what you want.
I'm not quite sure what you mean by "scan". If you're asking how to iterate over the string to process each character in turn, then in C it's:
for (char const * p = s; *p; ++p) {
// Do something with the character value *p
}
and in (modern) C++:
for (char c : s) {
// Do something with the character value c
}
If you're asking how to read the string as a line of input from the terminal, then in C it's
char s[SOME_SIZE_YOU_HOPE_IS_LARGE_ENOUGH];
fgets(s, sizeof s, stdin);
and in C++ it's
std::string s;
std::cin >> s; // if you want a single word
std::getline(std::cin, s); // if you want a whole line
If you mean something else by "scan", then please clarify.
You can simply get the ascii value of a char by casting it to type int:
char c = 'b';
int i = c; //i contains ascii value of char 'b'
Thus, in your example the code to get the ascii values of a string would look something like this:
#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;
int main()
{
string text = "John";
for (int i = 0; i < text.size(); i++)
{
cout << (int)text[i] << endl; //prints corresponding ascii values (one per line)
}
}
To get the corresponding char from an integer representing an entry in the ascii table, you just have to cast the int back to char again:
char c = (char)74 // c contains 'J'
The code given above was written in C++ but it basically works the same way in C (and many other languages as well I guess)
There is no way to turn a string of length 'x' into x variables. In C or C++ you can only declare a fixed number of variables. But probably you don't need to do what you are saying. Perhaps you just need an array, or most likely you just need a better way to solve whatever problem you are trying to solve. If you explain what the problem is in the first place, then I'm sure a better way can be explained.
Ya,I think there are some more better solutions are also available but this one also be helpful.
In C
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int main(){
char s[]="abc";
int cnt=0;
while(1){
if(s[cnt++]==NULL)break;
}
int *a=(int *)malloc(sizeof(int)*cnt);
for(int i=0;i<cnt;i++)a[i]=s[i];
for(int i=0;i<cnt-1;i++)printf("%d\n",a[i]);
return 0;
}
In C++
#include <iostream>
#include <string>
using namespace std;
int main(){
string s="abc";
//int *a=new int[s.length()];
//for(int i=0;i<s.length();i++)a[i]=s[i];
for(int i=0;i<s.length();i++)
cout<<(int)s[i]<<endl;
return 0;
}
I hope this one will be helpful..
yeah it's very easy ..just a demo
int main()
{
char *s="hello";
while(*s!='\0')
{
printf("%c --> %d\n",*s,*s);
s++;
}
return 0;
}
But make sure your machine is supporting the ASCII value format.
In C every char has one integral value associted with it called ASCII.
Using %d format specifier you can directly print the ASCII of any char as above.
NOTE: It's better to get good book and practice this kind of program yourself.
below is the prog i am compiling for replacing spaces with "%20" but when I run it output window shows blank and a message "arrays5.exe has occurred a prob"
#include <iostream>
#include<cstring>
using namespace std;
void method(char str[], int len) //replaces spaces with "%20"
{
int spaces, newlen,i;
for (i=0;i<len;i++)
if(str[i]==' ') spaces++;
newlen=len+spaces*2;
str[newlen]=0;
for (i=len-1;i>=0;i--)
{
if(str[i]==' ')
{
str[newlen-1]='0';
str[newlen-2]='2';
str[newlen-3]='%';
newlen=newlen-3;
}
else
{
str[newlen-1]=str[i];
newlen=newlen-1;
}
}
}
int main()
{
char str[20]="sa h ";
method(str,5);
cout <<str<<endl;
return 0;
}
Please help me finding the error.Thanks
spaces is uninitialised before you increment it.
You should give it an initial, default value.
An uninitialised variable will have a value which is undefined by the specification. This value could be 0, if you're lucky but it is highly likely that this value will be anything in the range of values which the datatype may represent.
Your program will compile and run fine when spaces is initialised properly.
I'm not fixing your problem, but providing a better solution. If you're using C++, then you should use the STL. You've got lots of classes and methods that do all of the job for you.
You could rewrite your 25 lines long method into this 4 lines long method(example included):
#include <iostream>
#include <string>
using namespace std;
std::string method(std::string str)
{
size_t index;
while((index = str.find(' ')) != std::string::npos)
str = str.replace(index, 1, "%20");
return str;
}
int main()
{
std::string str("sa h ");
str = method(str);
cout <<str<<endl; // outputs sa%20h%20
return 0;
}
I would suggest you use std::string, and use the .replace method. The reason your code doesn't work is because you're overwriting the input string in an odd way so I don't know if your expected output would be correct, however, the actual error you have is that you're potentially rewriting at index locations -3, -2, and -1. Consider the case where your first space is at index zero.
In C++, it's usually better to avoid char* unless you have a clear reason for doing so. As a matter of good style (this is somewhat subjective), I would suggest that you do NOT modify your input arguments directly, but instead return the result.
Ie, your method prototype should be:
std::string method(std::string str)
There is no-longer a need to pass the length of the string, because std::string takes care of that.