How to make the program receive a string

Hi, I'm trying to make a program that lets the user input one phrase each time and goes counting the number of phrases written, after each phrase it will ask if the person wants to continue writing/counting.. I'm using Borland(I'm aware that it's outdated unfortunately that's what my teacher is asking me to use)..

My problem is that I noticed when I input something with spaces the program closes.. so I tried using getline(cin,x) but I got error: "Call to undefined function 'getline'".. I'm not sure how I can make it receive a full phrase without it stopping.

Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<iostream>
#include<string>
using namespace std;

int main(){
int cont = 0;
string x, z;

while(1 == 1)
{
   cout<<"Write a phrase."<<endl;   cin>>x;
   cont++;
   if(cont == 1)
   {
      cout<<"You wrote "<<cont<<" phrase."<<endl<<endl;
      cout<<"If you want to continue, write \"YEAH\"."<<endl;
      cin>>z;
      if(z == "YEAH")
      {
      cout<<endl;
      }
      else
      {
      break;
      }
   }
   else
   {
      cout<<"You wrote "<<cont<<" phrases."<<endl<<endl;
      cout<<"If you want to continue write \"YES\"."<<endl;
      cin>>z;
      if(z == "YES")
      {
      cout<<endl;
      }
      else
      {
      break;
      }
   }
}

return 0;
}
Last edited on
Note that you need use the correct capitalisation. "YES" will do, but "Yes" won't.
I'm using Borland

Which version number please?
Maybe your compiler is so old that it doesn't know getline.
You can use this one instead:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
string GetLine()
{
  char ch=0;
  string buffer;

  while (cin.get(ch))
  {
    if (ch == '\n')
      return buffer;

    buffer += ch;
  }
  return buffer;
}
You can try doing it the "C way" (sort of).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
#include <stdio.h>

int main()
{
  const unsigned int CHAR_BUF = 100;
  char buff[CHAR_BUF]{ '\0' };

  std::cout << "Enter input: ";
  std::cin.getline(buff, CHAR_BUF, '\n'); //Can you use cin.getline() ?

  std::cout << "Entered \"" << buff << "\"" << std::endl;
  

  return 0;
}

accomplishes the task on my platform


Enter input: sdfsdf sd fs dfs d
Entered "sdfsdf sd fs dfs d"
Press any key to continue . . .


I have no idea why your teacher would be asking you to use that... There are far better options. Heck, you can get Code::Blocks with a standards-compliant (or almost compliant) compiler on pretty much every platform I can think of.
Topic archived. No new replies allowed.