C++ get char of array with loop

Hello,

How can I get char of array with for loop?
I don't want to use a pointer and the length of the string doesn't fix.

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{

	char myArray[100];

	for (int i = 0;  myArray[i] != '\n'; i++) // it doesn't work
	{
		cin >> myArray[i];
	}


	return 0;
}




1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{

	char myArray[100];

	for (int i = 0;  i < 100; i++) // the length of array doesn't fix
	{
		cin >> myArray[i];
	}


	return 0;
}
char myArray[100];This creates an array of 100 chars, each char with no defined value yet. myArray[i] will never be '\n' because that character is not fed into a string when using cin >>.

Why not just do this instead?

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string str;
    cin >> str;
    cout << "Entered: " << str << '\n';
}

?

If you must use char arrays, do
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
    char arr[100];
    
    // http://www.cplusplus.com/reference/istream/istream/getline/
    // "A null character ('\0') is automatically appended to the written sequence"
    cin.getline(arr, 100);
    
    cout << arr << '\n';
}


Your second code isn't necessarily wrong depending on context, but it does force you to type in 100 characters.

How can I get char of array with for loop?
What does this mean? What exactly is the goal?
Last edited on
Topic archived. No new replies allowed.