当我尝试输出字符串时,它不会输出空格后面的文本。它应该询问学生的姓名,然后在被要求时输出。这是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;
}
发布于 2011-11-10 00:36:42
你可以像这样使用getline
string abc;
cout<<"Enter Name";
getline(cin,abc);
cout<<abc;
Getline
发布于 2011-11-10 00:48:26
您应该使用getline()
函数,而不是简单的cin
,因为cin
只获取空格之前的字符串。
istream& getline ( istream& is, string& str, char delim );
istream& getline ( istream& is, string& str );
从is
中提取字符并将其存储到str
中,直到找到分隔符。
第一个函数版本的分隔符为delim
,第二个函数版本的分隔符为'\n‘(换行符)。如果在is中到达文件末尾,或者如果在输入操作期间发生其他错误,则提取也会停止。
如果找到分隔符,则提取该分隔符并将其丢弃,即不存储该分隔符,并在其之后开始下一个输入操作。
发布于 2011-11-10 00:33:18
另一种方法是使用std::string getline()函数,如下所示
getline(cin, studname);
这将得到整个换行符和换行符。但是任何前导/尾随空格都将出现在您的字符串中。
https://stackoverflow.com/questions/8068111
复制相似问题