string program

How would I write a short program using a string object which lets
the user type in as much text as s/he wants, then prints
out ONLY THE LETTERS from the string in a line?
I keep getting the compile error saying initializer fails to determine size of 'str', how would I fix this if the size/length/char count is dependant on the cin?

#include <stdio.h>
#include <ctype.h>
#include <iostream>
#include <locale>
using namespace std;

int main()
{
int i=0;
int a;
cin >> a;
char str[]= a;
while (str[i])
{
if (isalpha(str[i])) printf (str[i]);
else printf (" ", str[i]);
i++;
}
return 0;
}
This line is s**t
char str[]= a;

You can't do this.. This means nothing. If you want "user to enter as much text as he wants" you need dynamic memory allocation...

So, something like this (not tested, but should work...)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int size = 0;
int allocated = 100;
char* text = (char*)malloc(sizeof(char) * allocated);
char c;

do
{
  cin >> c;
  text[size++] = c;
  
  //check if you still have memory
  if(size == allocated) {
    allocated *= 2;
    text = realloc(text, sizeof(char) * allocataed);
  }
}  while(c != '\n');

//checking for letters looks good in your code 


Btw, this is C, not C++... If you want C++, use std::string and everything becomes much easier...
you can assign your input string to variable of std::string type and then run the loop over it like
for( int i = 0;i < str.size();i++)
{
logic for isalpha and printing those characters.
}


Topic archived. No new replies allowed.