【问题标题】:How to put information into a string using whitespace? (From an array)如何使用空格将信息放入字符串中? (来自数组)
【发布时间】:2014-11-26 03:23:47
【问题描述】:

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

“使用空格的位置,使用 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;}

【问题讨论】:

  • 这里有很多选择。提示:std::string(char*,int) 将从指定长度的指定char* 创建一个字符串,或者您可以将完整答案存储在std::string 中,然后使用std::string::substr() 在给定位置的情况下提取名字和姓氏空格,或者您可以使用for 循环一次将一个字符从answer1(从开头到空格,然后从空格到结尾)复制到其他地方,等等。另见stackoverflow.com/questions/4637139/…
  • 感谢您的回复,我的问题是我必须使用空格来完成此操作
  • 这就是所有这些解决方案所做的......“空白”是一个东西,而不是你可以用来做某事的工具......你在字符串中找到空白的位置,然后使用其中一个在该位置将其一分为二的工具。您不是“使用空格分割字符串”,而是“找到空格,然后在该位置分割字符串”。
  • 您介意给我举个例子,说明如何设置字符串 substr() 函数吗?我已经在谷歌和这里搜索过,但我一无所获:(
  • 您是否没有阅读我第一条评论中的链接,其中包含一个明确的示例...?我输入该评论并不是为了练习打字。

标签: c++ arrays string


【解决方案1】:

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

#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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    相关资源
    最近更新 更多