用输入流初始化一个字符串数组
时间: 2023-07-18 09:32:24 浏览: 52
可以使用Scanner类从控制台或文件读取输入流,并使用split方法将读取的字符串分割成一个字符串数组。下面是一个示例代码:
```java
import java.util.Scanner;
public class StringArrayExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一行字符串: ");
String input = scanner.nextLine();
String[] stringArray = input.split(" ");
System.out.println("分割后的字符串数组为: ");
for (String str : stringArray) {
System.out.println(str);
}
}
}
```
在上面的代码中,我们通过Scanner类从控制台读取输入,并使用split方法将输入的字符串分割成一个字符串数组。split方法使用空格作为分隔符。最后,我们遍历字符串数组并打印每个字符串。
相关问题
用c++输入流初始化一个字符串数组
可以使用C++中的`std::getline()`函数从输入流中读取一行字符串,然后使用`std::stringstream`将该字符串分割成一个字符串数组。下面是一个示例代码:
```c++
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string input;
cout << "请输入一行字符串: ";
getline(cin, input); // 从标准输入流中读取一行字符串
istringstream iss(input); // 使用输入字符串初始化 stringstream 对象
string str;
string stringArray[100]; // 假设最多有100个字符串
int index = 0;
while (iss >> str) { // 从 stringstream 中读取每个字符串
stringArray[index++] = str;
}
cout << "分割后的字符串数组为: " << endl;
for (int i = 0; i < index; i++) {
cout << stringArray[i] << endl;
}
return 0;
}
```
在上面的代码中,我们使用`std::getline()`函数从标准输入流中读取一行字符串,并使用该字符串初始化一个`std::stringstream`对象。然后,我们使用`>>`运算符从`std::stringstream`对象中依次读取每个字符串,并将它们存储在一个字符串数组中。最后,我们遍历字符串数组并打印每个字符串。
从键盘读入一行字符串,以空格作为分隔符,将内容存入字符串数组中。 (
好的,我理解了。可以开始回答您的问题了。
请使用以下代码来实现您的要求:
```
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string input;
getline(cin, input); // 从键盘读入一行字符串
stringstream ss(input); // 将字符串转换为字符流
string word;
string words[100]; // 定义字符串数组
int count = 0;
while (ss >> word) // 以空格作为分隔符,将内容存入字符串数组中
{
words[count] = word;
count++;
}
cout << "您输入的字符串为:" << input << endl;
cout << "字符串数组的内容为:" << endl;
for (int i = 0; i < count; i++)
{
cout << words[i] << endl;
}
return 0;
}
```
这段代码中,我们首先创建一个字符串变量`input`来保存用户从键盘输入的一行字符串。然后使用`getline`函数将输入读入到`input`变量中。
接着,我们创建一个字符流`ss`,并使用`input`变量将其初始化。然后,我们定义一个字符串变量`word`,以及一个字符串数组`words`和一个计数器变量`count`。
在循环过程中,我们使用`ss >> word`这样的语法,将以空格为分隔符的每个单词读入`word`中。接着将单词存入字符串数组`words`中,并将计数器变量`count`加1。
最后,我们输出用户输入的原始字符串和存储在字符串数组`words`中的所有单词。
希望这段代码可以满足您的要求。