-5
#include <bits/stdc++.h>

using namespace std;

vector<string> split(string str, char delimiter)
{
  vector<string> internal;
  stringstream ss(str);
  string tok;

  while(getline(ss, tok, delimiter))
  {
    internal.push_back(tok);
  }

  return internal;
}

int main() 
{
  freopen("in", "r", stdin);
  freopen("out", "w", stdout);
  int tt;
  scanf("%d", &tt);
  for (int qq = 1; qq <= tt; qq++) {
    printf("Case #%d: ", qq);

    char s[1234];

    stringstream ss;
    gets(s);
    for(int j = 0; s[j] ; j++) ss << s[j]; 

    vector<string> w = split(ss.str(), ' ');    
    for(int i = 0; i < w.size(); ++i)
    {
      printf("%s ", w[i].c_str());
    } 
    printf("\n");
  }
  return 0;
}

输入

5

this is a test

foobar

all your base

class

pony along

输出

Case #1: 

Case #2: this is a test 

Case #3: foobar 

Case #4: all your base 

Case #5: class 

我是 C++ 初学者。我正在尝试解决反向单词问题:https ://code.google.com/codejam/contest/351101/dashboard#s=p1

我无法弄清楚为什么我的输出给出了这个。

请帮我。

4

2 回答 2

1

gets()不是 C++ 库函数。这是一个C函数。freopen() 和()同上scanf

混合 C 库stdio函数和 C++ 输入/输出库函数会导致未指定的行为。

将所有代码转换为仅使用std::cinstd::coutstd::getline()其他 C++ 输入/输出库函数。

于 2016-03-19T01:32:38.273 回答
0

scanf吃的是5,但不是后面的换行符,因此您最终会在第一次getline调用时消耗该行的其余部分(由于5被吃掉,它是一个空行)。

在格式字符串中的格式代码后添加一个空格,scanf使其在之后消耗空格,或者为了安全起见,通过执行 a 读取数字getline,然后使用fscanf或更好地解析它,使用stringstream基于解析的方法来最小化cstdioiostream功能的混合。

于 2016-03-19T01:35:16.183 回答