2011-11-09 138 views
3

当我尝试输出字符串时,它不输出空格后的文本。它应该询问学生姓名,然后在询问时输出。这是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; 
} 
+0

可能的重复:http://stackoverflow.com/questions/8052009/returning-a-string(同样的问题,不同的上下文) – IronMensan

回答

3

你可以使用函数getline所以这样

string abc; 
cout<<"Enter Name"; 
getline(cin,abc); 
cout<<abc; 

Getline

2

cin喜欢用空白,打破东西,所以这就是为什么你只得到一个名字。可能的是,由于作业要求您抓住名字和姓氏,因此您可能会认为这些名称会被空格分隔。在这种情况下,你可以抓住两个分开,然后将它们连接起来:

string firstname = "default"; 
string lastname = "default"; 

cin >> firstname >> lastname; 

return firstname + " " + lastname; 
3

另一种方法是使用std ::字符串函数getline()函数这样

getline(cin, studname); 

这将让整个换行符和换行符。但是任何前导/尾随空格都会出现在你的字符串中。

0

为了让整条生产线,你需要使用函数getline代替>>:

getline(cin, myString); 
5

你应该使用getline()函数,而不是简单的cin,因为cin只在空白符之前得到字符串。从is并将它们存储到str

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

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

提取字符,直到一个分隔符是发现。

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

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