-4
#include <bits/stdc++.h>
using namespace std;
int main()
{
    char *str;
    gets(str);
    int size = strlen(*(&str));
    //How to iterate through this str which is acting like a string here
    return 0;
}

//I'm trying to print each char in a new line.

  • 5
    Find a good book and a good teacher -> your code is full of problems (it's not your fault, it's because of a bad book/tutorial/school/teacher). – Michael Chourdakis Feb 25 '22 at 08:22
  • You should first think about how to properly store the characters entered – Odysseus Feb 25 '22 at 08:27
  • 1
    The character pointer `str` does not point to any `char` object and is uninitialized. Use `std::string` instead and a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Jason Feb 25 '22 at 08:30
  • use `std::string`, `char *` is not recommended by `g++` compiler – Darth-CodeX Feb 25 '22 at 08:40

2 Answers2

1

Ignoring all the other problems, such as using an uninitialized pointer, using gets (it's so bad it's been removed from C and C++), including bits/stdc++.h, not using std::string and std::getline...

Using your size variable, you can use loop like this:

for(int index = 0 ; index < size ; ++index) {
    std::cout << "character at index " << index << " is '" << str[index] << "'\n";
}

But note that your code will crash at gets and never get to this loop. Please find better learning material to get started with C++!


PS. To get your code to not crash, change char *str; to char str[10000];... Then that program should run and you are unlikely to accidentally cause a buffer overflow. Still, I repeat, get better learning material!

hyde
  • 60,639
  • 21
  • 115
  • 176
1

The character pointer str doesn't point to any char object and has not been initialized.

Second, the function gets has been deprecated in C++11 and removed in C++14.

A better way would be to use std::string instead as shown below:

#include <string>
#include <iostream>
int main()
{
    std::string str;
    //take input from user
    std::getline(std::cin, str);

    //print out the size of the input string 
    std::cout << str.size() << std::endl;

    //iterate through the input string 
    for(char& element: str)
    {
        std::cout<<element<<std::endl;
    }
}
Jason
  • 36,170
  • 5
  • 26
  • 60