如何使用空格将信息放入字符串中?(来自数组)

How to put information into a string using whitespace? (From an array)

本文关键字:数组 字符串 空格 何使用 信息      更新时间:2023-10-16

困惑.. 我的老师让我把这些信息从数组中放入一个字符串中......以下是她给我的确切方向:

"使用空格的位置,使用 this 和适当的字符串函数将名字存储在 fname 中,将姓氏存储在 lname 中(两个字符串变量)中。"

isspace 函数为我找到了空格,我把它放在变量"y"中,正如您将在下面的代码中看到的那样。 但我不知道如何使用空格将从数组输入的字符放入两个单独的字符串变量中!

。任何帮助将不胜感激!

这是我的代码:

// Zachary Law Strings.cpp
#include <iostream>
using namespace std;
#include <string>
#include <iomanip>

int main()
{   int x, i,y;
char name[] = "Please enter your name: ";
char answer1 [80];
i=0;
y=0;
cout << name;
cin.getline(answer1, 79);
cout << endl;
x=strlen(answer1);
 for (int i = 0; i < x; i++){
    cout << answer1[i] << endl;
    if (isspace(answer1[i])) 
    {y=y+1;}}
 cout << endl << endl;
 cout << setw(80) << answer1;
 cout << y;


return 0;}

你可以看到这个代码...我已经编辑了你的代码...希望,你会得到这个... :)

#include <iostream>
using namespace std;
#include <string>
#include <string.h>
#include <iomanip>
int main()
{
    int x, i,y,fg=0,z;
    char name[100];
    string answer;
    i=0;
    y=0;
    cout<<"Enter Your First & Last Name:";
    cout << endl;
    cin.getline(name,100);
    x=strlen(name);
    for (int i = 0; i < x; i++){
        if (!fg&&isspace(name[i]))
        {
            y=i;
            fg=1;
        }
        else if(fg==1&&!isspace(name[i]))
        {
            z=i;
            fg=2;
        }
        answer+=name[i];
    }
    string fname=answer.substr(0,y);
    cout<<fname<<endl;
    string lname=answer.substr(z,x-z);
    cout<<lname<<endl;
    return 0;
}