1

I'm trying to input a sequence of words using character array. I don't want to use string from STL. Where am I going wrong?

int n;
cout<<"Enter the number of words:";
cin>>n;
char **s = new char*[n];
for(int i=0;i<n;i++)
{
  char *s = new char[10];
  cin>>s[i];

}
5
  • 2
    You'll benefit greatly by using std::vector instead of managing the memory yourself. Something like std::vector<std::vector<char>>(n, std::vector<char>(10)). If you are storing strings std::vector<std::vector<std::string>>(n) Commented Oct 26, 2014 at 1:00
  • 1
    I don't want to use string from STL Any reason why? Commented Oct 26, 2014 at 1:01
  • Just beacuse I want to learn how it would work with char. Commented Oct 26, 2014 at 1:18
  • I also think you should be using Vector. Commented Oct 26, 2014 at 1:22
  • @lostboy_19 Just beacuse I want to learn how it would work with char So if you want to learn, look at the thousands of examples of properly coded dynamic array classes right here on SO and other sites. No need to throw together non-working code and wonder what to do next. Commented Oct 27, 2014 at 15:42

3 Answers 3

2

Look at what char *s = new... is initialising. It is not the same as the location that s[i] refers to.

Actually it's wrong for two reasons -- one, char *s is a new declaration within the scope of the for loop, and two because it is not indexed by i.

I think you need s[i] = new char[10] without the char declaration, because s is a double pointer, so s[i] is already a pointer.

Apologies for so many edits, its too late at night....

Sign up to request clarification or add additional context in comments.

Comments

1

Use

char ch[n+1];
for(int i = 0;i<n;i++)
`cin>>ch[i];
ch[n] = '\0';
cout<<ch<<endl;

Comments

1

By using a cin to a char array, you can easily get in trouble, with buffer overrun, as you can see on this https://stackoverflow.com/a/15642881/194717

You can do something like the code below, but note that a clean way to do this task is to use vector and string:

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    int n;
    cout << "Enter the number of words:";
    cin >> n;

    //vector<string> list(n);
    vector<char[100]> list(n);

    // Request from user the words
    for (int i = 0; i < n; i++)
        cin >> list[i];

    // Display the list
    //for each (string word in list)
    //  cout << word << endl;
    for (int i = 0; i < n; i++)
        cout << list[i] << endl;

    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.