打印带空格的字符串

Sam*_*nna 4 c++

当我尝试输出字符串时,它不会在空格后输出文本.它应该询问学生姓名,然后在被问到时输出.这是C++.我没有更多信息要提供,但该网站不会让我发布它所以这句话在这里.

/***************************************************/
/* Author:     Sam LaManna                         */
/* Course:     CSC 135 Lisa Frye                   */
/* Assignment: Program 4 Grade Average             */
/* Due Date:   10/10/11                            */
/* Filename:   program4.cpp                        */
/* Purpose:    Write a program that will process   */
/*             students are their grades. It will  */
/*             also read in 10 test scores and     */
/*             compute their average               */
/***************************************************/

#include <iostream>     //Basic input/output
#include <iomanip>      //Manipulators

using namespace std;

string studname ();     //Function declaration for getting students name

int main()
{
  string studentname = "a";     //Define Var for storing students name

  studentname = studname ();    //Store value from function for students name

  cout << "\n" << "Student name is: " <<studentname << "\n" << "\n";     //String output test

  return 0;
}

/***************************************************/
/* Name: studname                                  */
/* Description: Get student's first and last name  */
/* Paramerters: N/A                                */
/* Return Value: studname                          */
/***************************************************/

string studname()
{
  string studname = "default";


  cout << "Please enther the students name: ";
  cin >> studname;

  return studname;
}
Run Code Online (Sandbox Code Playgroud)

小智 5

您应该使用getline()函数而不是简单函数,仅cin用于cin在空格之前获取字符串.

istream& getline ( istream& is, string& str, char delim ); 

istream& getline ( istream& is, string& str );
Run Code Online (Sandbox Code Playgroud)

从中提取字符is并将其存储到str找到分隔符字符.

分隔符delim用于第一个函数版本,'\n'(换行符)用于第二个函数版本.如果到达文件末尾或者在输入操作期间发生某些其他错误,则提取也会停止.

如果找到分隔符,则将其提取并丢弃,即不存储分隔符,并且在其之后开始下一个输入操作.