I'm having trouble finding a way of going through each character of a pointer to an array of chars.
1 2 3 4 5 6 7 8 9 10 11 12 13
#include "std_lib_facilities.h" // Comes with the book I'm reading
int main()
{
char* input;
char temp = 0;
while(cin >> temp && temp != '!')
{
input = newchar(temp);
}
// How do I print the characters in char* input one by one?
return 0;
}
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
constint size = 100;
char array[size]; // here the input will be stored
cout << "Please enter some text:" << endl;
cin.getline(array, size); // get up to size-1 characters from user
char* input = array; // input points to the first character of the array
while (*input) // test current character is not null terminator
{
char temp = *input; // get current character in temp
cout << temp; // output it
++input; // increment to next character
}
cout << endl;
return 0;
}
Write a program that reads characters from cin into an array that you allocate on the free store. Read individual characters until an exclamation mark (!) is entered. Do not use std::string. Do not worry about memory exhaustion.
I did the exercise, but I want to make sure that what I entered is actually stored. But I can't find I way to print anything from the array.
This is how the book taught me to allocate and initialize an array:
1 2 3 4 5 6
char* a = newchar[10];
for(int i = 0; i < 10; ++i)
{
a[i] = 65 + i;
cout << a[i] << "\n"; // prints A, B, C, etc..
}
So why doesn't my code print out char* input? I tried it without a for-loop like this:
The purpose of the exercise is to demonstrate the limited nature of arrays and the advantage of using standard class std:;string (exercise 8).
So the code of the exercise 7 can look very simply
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
int main()
{
const size_t N = 10;
char *s = newchar[N];
char c;
size_t i = 0;
// wait until the program will abort:)
while ( std::cin >> c && c != '!' ) s[i++] = c;
}
Only when you will do exercise 8 you may not write s[i]. Instead you can use either operator += or member function push_back or even append. For example
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
#include <string>
int main()
{
const size_t N = 10;
std::string s;
s.reserve( N );
char c;
while ( std::cin >> c && c != '!' ) s += c; // or s.push_back( c ) or s.append( 1, c )
}