Sorry if this has been asked before, I did search and found similar questions but none with an array of strings.
I have a dynamically allocated array of strings, and I am trying to receive user input ignoring the whitespace. I have tried getline(cin,StringArray[0]); and this does not work, I have also tried is using a pointer rather than accessing the array through brackets.
1 2 3 4
string *billName;
cin>>size;
billName = new string[size];
getline(cin,billName[0]);
@Superdude:
Actually, TC's syntax is correct. TC is simply using dynamic memory to allocate an array of an arbitrary size.
@TC:
There isn't a standard function to just ignore all whitespace, though you could write a function to go through the string after you have read it and remove any characters you don't like.
#include <cstdio>
#include <cctype>
#define MAXWORDS 100
int getInput(char *input, int=MAXWORDS);
int main() {
char words[MAXWORDS];
while (getInput(words));
return 0;
}
int getInput(char *input, int maxlen) {
int d;
char * w = input;
while (isspace(d=getchar())) //ignore space
;
if ( d == EOF ) {
*w = '\0';
return 0;
}
for ( *w++ = d ; --maxlen ; *w++ = d )
if ( (d=getchar()) == '\n' or d == EOF ) break;
*w = '\0';
return *input;
}
Basically I'm trying to ignore the spacing between words. It's going to be a monthly bill program, and I'm trying to accommodate for bills that are more than one word, ie: Capital One. Thanks for all of your input so far.
You were on the right track then. Why wasn't the code in the original post working for you?
1 2 3 4 5 6 7 8 9 10
#include <iostream>
int main()
{
std::string name ;
std::cout << "Enter bill name: " ;
std::getline(std::cin, name) ;
std::cout << "Bill name is \"" << name << "\"\n" ;
}
Hey Cire, thanks. I believe my issue to be because I am trying to getline an array using subscripts. I may need to try it as a pointer rather than using the subscripts, since that is when it does not work for me.
Given the code in the original post, I suspect your code suffers from another issue, namely that of mixing unformatted and formatted input. After you do cin >> size; a newline remains in the input stream that is encountered by the call to getline, causing the extraction of an empty string.
#include <string>
#include <iostream>
int main()
{
unsigned nBills;
std::cout << "How many bills will you enter?\n";
std::cin >> nBills;
std::string* bills = new std::string[nBills];
std::cout << "Please enter the bill names.\n";
std::cin >> std::ws ; // Remove leading whitespace.
for ( unsigned i=0; i<nBills; ++i )
std::getline(std::cin, bills[i]);
std::cout << "The bills you entered are:\n";
for (unsigned i = 0; i < nBills; ++i)
std::cout << '\t' << bills[i] << '\n';
}