Write a string that enter a name of a company

closed account (G6ko1hU5)
Please can anyone help I'm trying to write this code but I don't understand which is the length and how to let it type only my written names
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>
#include<string>
using namespace std;

int main() {
	cout << "Welcome to our program." << endl;
	cout << "Enter the name of the company: ";
	string companyname[3];
	for (int i = 0; i < 3; i++)
		cin >> companyname[i];
	for (int i = 0; i < 50; i++)
		cout <<"the name is: " << companyname[i] << " ";
	cout << endl;
	system("pause");
	return 0;
}
Last edited on
There are C-strings, which are really just an array of char:
 
char im_a_c_string[ 50 ];

This string has enough room for up to 49 characters plus a null-terminator. Whenever you mess with it, you must be careful to never use more than the available 49 characters.
1
2
std::strcpy( im_a_c_string, "Hello " );
std::strcat( im_a_c_string, "world!" );  // there is no guarantee that all this fits! 


C++ makes life easy, and does all the array stuff for you:
 
std::string im_a_cpp_string;

You no longer have to care about how many characters are in the array, because C++ will do it for you.
1
2
im_a_cpp_string = "Hello ";
im_a_cpp_string += "world!";  // no worries! 


Hence, to get a company name, just declare a string variable and use it, much like an int:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
using namespace std;

int main()
{
  cout << "Hello!\n";

  string company_name;
  cout << "Company name? ";
  getline( cin, company_name );

  cout << "Good job! Your company is " << company_name << "\n";
}

The next thing to do is compile and run programs you create. The more you mess with it, the quicker things make sense.

Hope this helps.
closed account (G6ko1hU5)
Thank you for your help that is what I wanted, I didn't know how many characters I want to use.
Topic archived. No new replies allowed.