strcmp分段错误

2 c c++

这是一个来自spoj的问题.与算法无关,但只是c

样本输入

2

a a bb cc def ghi

aaaaa bb bb bb bb cc

样本输出

3

它计算相同单词的最长序列 http://www.spoj.pl/problems/WORDCNT/ 这个单词少于20个字符但是当我运行它时,它会给出分段错误.我使用eclipse调试它.这是崩溃的地方

if (strcmp(previous, current) == 0)
                currentLength++;
Run Code Online (Sandbox Code Playgroud)

以下消息

"strcmp()在0x2d0100没有可用的来源"有什么问题?

#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
using namespace std;
int main(int argc, const char *argv[])
{
    int t;
    cin >> t;
    while (t--) {
        char line[20000], previous[21], current[21], *p;
        int currentLength = 1, maxLength = 1;
        if (cin.peek() == '\n') cin.get();
        cin.getline(line, 20000);

        p = strtok(line, " '\t''\r'");
            strcpy(previous, p);

        while (p != NULL) {
            p = strtok(NULL, " '\t''\r'");
            strcpy(current, p);

            if (strcmp(previous, current) == 0)
                currentLength++;
            else
                currentLength = 1;
            if (currentLength > maxLength)
                maxLength = currentLength;
        }
        cout << maxLength << endl;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ork 9

问题可能出在这里:

    while (p != NULL) {
        p = strtok(NULL, " '\t''\r'");
        strcpy(current, p);
Run Code Online (Sandbox Code Playgroud)

输入循环时p可能不为NULL.
在使用strcpy时它可能为NULL.

一个更正确的循环形式是:

    while ((p != NULL) && ((p = strtok(NULL, " \t\r")) != NULL))
    {
        strcpy(current, p);
Run Code Online (Sandbox Code Playgroud)

注意.使用C++对流进行标记更容易.

std::string  token;
std::cin >> token;  // Reads 1 white space seoporated word
Run Code Online (Sandbox Code Playgroud)

如果要标记一行

// Step 1: read a single line in a safe way.
std::string line;
std::getline(std::cin, line);

// Turn that line into a stream.
std::stringstream  linestream(line);

// Get 1 word at a time from the stream.
std::string token;
while(linestream >> token)
{
    // Do STUFF
}
Run Code Online (Sandbox Code Playgroud)