【问题标题】:i want to print every slot of my array at a new line我想在新行打印我的数组的每个插槽
【发布时间】:2014-12-10 16:13:25
【问题描述】:

这是我当前的代码,我必须在新行上打印我名字的每个世界

include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
int main ()
{
    string a;
    char j[100];
    int i, c, b; 
    cout <<"enter your full  name ";
        getline(cin,a);
        cout << " ur name is " << a << endl;
c=a.size(); 
for (b=0; b<=c; b++)
{
j[b]=a[b];
j[b]='\0';
}
system ("pause");
return 0; 
}

如何在新行上打印我名字的每一部分?例如:输入:geroge ashley mark。输出:乔治(换行)阿什利(换行)标记

【问题讨论】:

  • 你使用了在你的代码中产生新行的东西,所以我真的对你的问题感到困惑。
  • 你为什么还要复制到一个数组中(并且一开始就做错了)?
  • 因为用户名可能不是单一的。所以我不想放超过 1 cin
  • 你能举一个输入和预期输出的例子吗?
  • Checkout stackoverflow.com/questions/236129/split-a-string-in-c(它甚至是 C++ FAQ 的一部分)

标签: c++ visual-studio-2010


【解决方案1】:

这是一个有点复杂的方法,我更喜欢 cmets 中显示的方法。但是,如果您想避免使用字符串流,这里有另一种方法来实现您正在寻找的东西。它还将支持逗号分隔的名称。

#include "stdafx.h"

#include "iostream"
#include "string"
using namespace std;
int main()
{
    string a;
    char j[100];
    int i, c, b;
    cout << "enter your full  name ";
    getline(cin, a);
    cout << " ur name is " << a << endl;
    c = a.size();

    bool space = false;

    for (auto iter = a.begin(); iter != a.end(); iter++)
    {
        if (isalpha(*iter) == false)
        {
            if (space == false)
            {
                cout << std::endl;
                space = true;
            }
        }
        else
        {
            cout << (*iter);
            space = false;
        }
    }
    system("pause");
    return 0;
}

【讨论】:

  • 我怎样才能在新行上打印我名字的每一部分?我不认为 OP 想要每行一个字符。
猜你喜欢
  • 1970-01-01
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
  • 2020-09-03
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
  • 2021-10-01
相关资源
最近更新 更多