我怎么能像这样输入字符串?

时间:2015-09-05 16:27:31

标签: c++

如果我有一个包含未知单词数的字符串,我必须在C ++中用多个字符串扫描它。我该怎么做?

For eg: 
"I am a boy". I want, each of these individual words to be in a string. 
"My name is John Lui". Each of these as well. 

我能想到的一种方法是在c ++中使用getline然后解析整个字符串,直到找到个字符并存储在单独的字符串中。我想知道有更好的方法吗?谢谢!

另外,我想知道,在delimiter命令中使用getline时,getline基本上扫描输入字符串,直到找不到点分隔符,并将字符串的那部分放入新的串。但是,我想知道,如果分隔符根本不存在,那么会发生什么?它会抛出一个异常还是输入整个字符串直到换行符?谢谢!

1 个答案:

答案 0 :(得分:2)

但是你可以使用 std :: getline

  

使用字符串而不是char数组。它更容易使用字符串   因为他们知道他们的尺寸,他们自动成长等等,你不必这样做   担心空终止字符等等。也是   可以使用适当的方法将char数组转换为字符串   string contructor。

您可以stringstream执行此操作:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test script.</title>
</head>

<body>
<?php
    $host = "localhost";
    $username = "testing";
    $password = "*******";
    $database = "zadmin_testing";
    $textFilesArray = scandir("data");
        foreach( $textFilesArray AS $textFile )
            {
                $handle = fopen($textFile, "r");
                # Get the lines of the file
                $dateCreated = fgets($handle);
                $videoTitle = fgets($handle);
                $videoType = fgets($handle);
                $videoImage = fgets($handle);
                $videoGenre = fgets($handle);
                $videoViewerRating = fgets($handle);
                $videoPath = fgets($handle);
                $videoMovieRating = fgets($handle);
                $videoDesc = fgets($handle);
            }

    // Creating my connection
{
    $conn = mysql_connect("$host","$username","$password");
    //Checking connection
    if (!$conn)
        {
            die('Could not connect: ' . mysql_error());
        }
}
    //My query
    $query = "INSERT INTO `zadmin_testing`.`videos` (`date`, `title`, `type`, `cover`, `genre`, `vrating`, `path`, `mrating`, `description`) VALUES     ('$dateCreated',   '$videoTitle', '$videoType', '$videoImage', '$videoGenre', '$videoViewerRating', '$videoPath', '$videoMovieRating', '$videoDesc')";

{
    //Run my query
    mysql_query($query);
}

echo "<h2>testing 12</h2>";

  mysql_close($conn);

?>
</body>
</html>

输入:// stringstream::str #include <string> // std::string #include <iostream> // std::cout #include <sstream> // std::stringstream, std::stringbuf using namespace std; int main () { std::string str; getline( std::cin, str ); std::stringstream ss; ss<<str; std::string s; while(ss>>s) { std::cout << s << '\n'; } return 0; }

输出:

I am a boy

如果您认为,您希望每个单词都存储在I am a boy 中,您可以这样做:

vector