Риски, связанные с вводом строк
Использование строк в массивах
Два наиболее распространенных метода помещения строки в массив заключаются:
· в инициализации массива строковой константой и
· чтением из клавиатурного или файлового ввода в массив.
Программа 2
// strings.cpp -- storing strings in an array
#include <iostream>
#include <cstring> // for the strlen() function
int main()
{
using namespace std;
const int Size = 15;
char name1[Size]; // empty array
char name2[Size] = "C++owboy"; // initialized array
cout << "Howdy! I'm " << name2;
cout << "! What's your name?\n";
cin >> name1;
cout << "Well, " << name1 << ", your name has ";
cout << strlen(name1) << " letters and is stored\n";
cout << "in an array of " << sizeof(name1) << " bytes.\n";
cout << "Your initial is " << name1[0] << ".\n";
name2[3] = '\0'; // set to null character
cout << "Here are the first 3 characters of my name: ";
cout << name2 << endl;
getchar();
getchar();
return 0;
}
сокращение строки с помощью записи \0 символа в 4-й элемент.
Назначение программы из листинга прочитать имя пользователя и название любимого десерта, введенные с клавиатуры, и затем отобразить эту информацию.
Программа 3
// instr1.cpp -- reading more than one string
#include <iostream>
int main()
{
using namespace std;
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
cout << "Enter your name:\n";
cin >> name;
cout << "Enter your favorite dessert:\n";
cin >> dessert;
cout << "I have some delicious " << dessert;
cout << " for you, " << name << ".\n";
getchar();
getchar();
getchar();
return 0;
}
У класса istream, экземпляром которого является cin, есть функции-члены, предназначенные для строчно-ориентированного ввода:
getline() и get().
Оба читают полную строку ввода – т.е. вплоть до символа новой строки.
Он читает полную строку в массив name, предполагая, что строка состоит не более чем из 19 символов.
Программа 4
// instr2.cpp -- reading more than one word with getline
#include <iostream>
int main()
{
using namespace std;
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
cout << "Enter your name:\n";
cin.getline(name, ArSize); // reads through newline
cout << "Enter your favorite dessert:\n";
cin.getline(dessert, ArSize);
cout << "I have some delicious " << dessert;
cout << " for you, " << name << ".\n";
getchar();
return 0;
}
Программа 5
// instr3.cpp -- reading more than one word with get() & get()
#include <iostream>
int main()
{
using namespace std;
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
cout << "Enter your name:\n";
cin.get(name, ArSize).get(); // read string, newline
cout << "Enter your favorite dessert:\n";
cin.get(dessert, ArSize).get();
cout << "I have some delicious " << dessert;
cout << " for you, " << name << ".\n";
getchar();
return 0;
}